1

i have a XML document that looks like this:

<body>
   <item id="9982a">
      <value>ab</value>
   </item>
   <item id="9982b">
      <value>abc</value>
   </item>
   etc...
</body>

Now, i need to get the value for a key, the document is very very big, is there any way to go directly to the key when i know the id? Rather then loop it?

Something like:

  $xml = simplexml_load_string(file_get_contents('http://somesite.com/new.xml'));
  $body = $xml->body;
  $body->item['id'][9982a]; // ab

?

IMSoP
  • 89,526
  • 13
  • 117
  • 169

3 Answers3

1

xpathis your friend, you can stay with simplexml:

$xml = simplexml_load_string($x); // assume XML in $x
$result = $xml->xpath("/body/item[@id = '9982a']/value")[0]; // requires PHP >= 5.4

echo $result;

Comment:

in PHP < 5.4, do...

$result = $xml->xpath("/body/item[@id = '9982a']/value");
$result = $result[0];

see it working: https://eval.in/101766

michi
  • 6,565
  • 4
  • 33
  • 56
  • Note that the "requires PHP >= 5.4" comment only refers to the `[0]` part. For older versions, assign `$result` to the result of `->xpath()`, then `echo $result[0]` – IMSoP Feb 15 '14 at 01:58
0

Yes, use Simple HTML DOM Parser instead of SimpleXML.

It would be as easy as:

$xml->find('item[id="9982b"]',0)->find('value',0)->innertext;
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
0

It is possible with DOMXpath::evaluate() to fetch scalar values from a DOM using xpath expressions:

$xml = <<<'XML'
<body>
   <item id="9982a">
      <value>ab</value>
   </item>
   <item id="9982b">
      <value>abc</value>
   </item>
</body>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

var_dump(
  $xpath->evaluate('string(//body/item[@id="9982b"]/value)')
);
ThW
  • 19,120
  • 3
  • 22
  • 44