2

Using PHP's simplexml_load_string how do I get the values of a tag has a particular attribute set to a particular value?

1

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0
    <?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`
    ?>

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.