Reputation: 13061
i have an xml like:
<AvailableCatgs>
<AvailableCatg>
<CategoryCode>01</CategoryCode>
<Pr>1857.48</Pr>
</AvailableCatg>
<AvailableCatg>
<CategoryCode>13</CategoryCode>
<Pr>1900.40</Pr>
</AvailableCatg>
<AvailableCatg>
<CategoryCode>09</CategoryCode>
<Pr>22.3</Pr>
</AvailableCatg>
</AvailableCatgs>
I have to loop all AviableCatgs
and take value of CategoryCode
and Pr
. What i've done is:
$xpath = new DOMXPath($mainXml);
$path = "//AvailableCatg";
$res = $xpath -> query($path);
foreach ($res as $aviable) {
print_r($aviable->CategoryCode->nodeValue);
}
But it doesn't print me nothing... How can i do? thanks!!
Upvotes: 1
Views: 7037
Reputation: 1121
You can use:
(string) current($xml->xpath("//group[@ref='HS_TYP']"))
Upvotes: 0
Reputation: 59709
You can do this with relative XPath queries, like this:
$doc = new DOMDocument;
$doc->loadXML( $xml); // Your XML from above
$xpath = new DOMXPath( $doc);
foreach( $xpath->query( "//AvailableCatg") as $el) {
$ccode = $xpath->query( 'CategoryCode', $el)->item(0); // Get CategoryCode
$pr = $xpath->query( 'Pr', $el)->item(0); // Get Pr
var_dump($ccode->nodeValue . ' ' . $pr->nodeValue);
}
This will print:
string(10) "01 1857.48"
string(10) "13 1900.40"
string(7) "09 22.3"
Upvotes: 2
Reputation: 12851
You could do this easily with SimpleXml:
<?php
$xml=<<<x
<AvailableCatgs>
<AvailableCatg>
<CategoryCode>01</CategoryCode>
<Pr>1857.48</Pr>
</AvailableCatg>
<AvailableCatg>
<CategoryCode>13</CategoryCode>
<Pr>1900.40</Pr>
</AvailableCatg>
<AvailableCatg>
<CategoryCode>09</CategoryCode>
<Pr>22.3</Pr>
</AvailableCatg>
</AvailableCatgs>
x;
$s= simplexml_load_string($xml);
$res=$s->xpath('//AvailableCatg');
foreach ($res as $aviable) {
echo $aviable->CategoryCode, " -- ", $aviable->Pr, "<br/>";
}
?>
Upvotes: 1