1

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!!

Jayyrus
  • 12,961
  • 41
  • 132
  • 214

3 Answers3

2

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" 
nickb
  • 59,313
  • 13
  • 108
  • 143
  • Sorry :) soap server gives me an xml different from documentation.. so the correct tag is AvailableCategory.. so your code works good!!! thanks!!!!!!!!!!!!! :) – Jayyrus Aug 04 '12 at 16:29
1

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/>";
}
?>
MilMike
  • 12,571
  • 15
  • 65
  • 82
0

You can use:

(string) current($xml->xpath("//group[@ref='HS_TYP']"))
HKandulla
  • 1,101
  • 12
  • 17