how to loop through xml using php with different nodes ← (PHP)

here is my xml I want to loop propertyList and get residential and rental nodes, can someone help me to know how can I do it, also when I print_r the propertylist node it returns null array

<propertyList>
<residential modTime="2020-11-10-11:35:06" status="current">
<agentID/>
<uniqueID>eagle_659872</uniqueID>
<authority value="exclusive"/>
<underOffer value="no"/>
<isHomeLandPackage value="no"/>
<listingAgent id="1">
  <name>Matt Luff</name>
</listingAgent>
<price display="yes">900000</price>
<priceView/>
<landDetails>
  <area unit="squareMeter"/>
  <frontage/>
  <depth side="left"/>
  <depth side="right"/>
  <depth side="rear"/>
 </landDetails>
 </residential>


<rental modTime="2020-11-09-12:56:01" status="current">
<agentID/>
<uniqueID>eagle_662855</uniqueID>
<listingAgent id="1">
  <name>Leasing Specialists </name>
</listingAgent>
<priceView>$430 per week</priceView>
<bond>1720</bond>
 <landDetails>
  <area unit="squareMeter"/>
  <frontage/>
  <depth side="left"/>
  <depth side="right"/>
  <depth side="rear"/>
 </landDetails>
 </rental>
 </propertyList>

Answer



Solution:<|/h4>

Use Xpath expressions. It allows you to fetch nodes and values from the DOM.<|/p>

$document = new DOMDocument();
$document->loadXML(getXML());
$xpath = new DOMXpath($document);

$expression = '/propertyList/residential|/propertyList/rental';
foreach ($xpath->evaluate($expression) as $property) {
    echo $property->localName, "\n";
    echo 'ID: ', $xpath->evaluate('string(uniqueID)', $property);
    echo 'Price: ', $xpath->evaluate('string(priceView)', $property);
    echo "\n";
}
<|/code><|/pre>

Output:<|/p>

residential
ID: eagle_659872
Price: 

rental
ID: eagle_662855
Price: $430 per week
<|/code><|/pre>

An expression like /propertyList/residential<|/code> will return nodes matching this location path. <|/code> separates alternative expressions. An starting |/<|/code> anchors the expression to the document root.<|/p>

$xpath->evaluate('string(uniqueID)', $property)<|/code> evaluates the expression string(uniqueID)<|/code> with the $property<|/code> node as context. It contains a string cast, so it will return the text content of the first uniqueID<|/code> child element node.<|/p>

This are only the most basic features. Xpath allows for a lot more complex expressions with conditions.<|/p>

Source