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

5

1 Answer 1

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 `` 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 `` 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 ;-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.