Using PHP's simplexml_load_string how do I get the values of a tag has a particular attribute set to a particular value?
2 Answers
Once you have loaded your XML data, you should be able to use the SimpleXMLElement::xpath method to do an XPath query on it, to find a specific element.
For example, considering your have an XML String, and load it this way :
$xmlString = <<<TEST
<root>
<elt plop="test">aaa</elt>
<elt plop="huhu">bbb</elt>
</root>
TEST;
$xml = simplexml_load_string($xmlString);
You could use the following portion of code to find the <elt> tag for which the plop attribute has the value huhu :
$elt = $xml->xpath('//elt[@plop="huhu"]');
var_dump($elt);
And you'd get this kind of output :
array
0 =>
object(SimpleXMLElement)[2]
public '@attributes' =>
array
'plop' => string 'huhu' (length=4)
string 'bbb' (length=3)
Comments
<?php
// heredoc use
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;
$xml = simplexml_load_string($string);
echo $xml->title; // you can get "Forty What?" value`enter code here`
?>