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

?

3 Answers 3

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

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

1 Comment

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]
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;

Comments

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

Comments

Your Answer

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