-1

how can i get the values of a,b and c from the following xml code?

<result name="response" f="139" c="0">
−
<doc score="5.06756" pos="0">
<snippet name="a" highlighted="yes">example</snippet>
<snippet name="b" highlighted="yes">bexample</snippet>
<snippet name="c">cexample</snippet>


</doc>
</result> 

I tried to print the nodes, but It failed:

$xmlDoc = new DOMDocument();
$xmlDoc->load($content);

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
  {
  print $item->nodeName . " = " . $item->nodeValue . "<br />";
  }

Can anyone tell me how I can parse it? I cannot use simple xml, so I am moving to Dom.

HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
raagavan
  • 951
  • 3
  • 12
  • 16
  • 1
    possible duplicate of [Regular expression for grabbing the href attribute of an A element](http://stackoverflow.com/questions/3820666/regular-expression-for-grabbing-the-href-attribute-of-an-a-element) – Gordon Mar 02 '11 at 12:12
  • possible duplicate of [XML lang parse in PHP](http://stackoverflow.com/questions/3996444/xmllang-parse-in-php/3996478#3996478) – Gordon Mar 02 '11 at 12:15
  • possible duplicate of [How to extract a node attribute from XML using PHP's DOM Parser](http://stackoverflow.com/questions/3993302/how-to-extract-a-node-attribute-from-xml-using-phps-dom-parser/3995983#3995983) – Gordon Mar 02 '11 at 12:17
  • possible duplicate of [DOMDocument::load Getting attribute value](http://stackoverflow.com/questions/4757587/domdocumentload-php-getting-attribute-value/4757670#4757670) – Gordon Mar 02 '11 at 12:18
  • possible duplicate of [Read XML properties](http://stackoverflow.com/questions/3085474/php-read-xml-properties/3085761#3085761) – Gordon Mar 02 '11 at 12:19

1 Answers1

1

Using DOM allows you to use several distinct ways of extracting informations.
For example, you could work with :


As an example, here's a portion of code that demonstrates how to use the first solution to extract all <snippet> tags :

$snippets = $xmlDoc->getElementsByTagName('snippet');
foreach ($snippets as $tag) {
  echo $tag->getAttribute('name') . ' = ' . $tag->nodeValue . '<br />';
}

And you'd get this output :

a = example
b = bexample
c = cexample


And, as another example, here's a solution that demonstrates how to use the second solution, to do a more complex query on the XML data -- here, extracting the <snippet> tag that as it's name attribute with a value of a :

$xpath = new DOMXPath($xmlDoc);
$snippetsA = $xpath->query('//snippet[@name="a"]');
if ($snippetsA->length > 0) {
  foreach ($snippetsA as $tag) {
    echo $tag->getAttribute('name') . ' = ' . $tag->nodeValue . '<br />';
  }
}

Which only gets you one result -- the corresponding tag :

a = example

Starting from here, the possibilities are almost limitless ;-)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663