user2571510
user2571510

Reputation: 11377

PHP: Get specific value from simplexml array

I am pretty new to PHP an XML and hope you can help me with this. Searching the forum didn't help me yet to find an answer to my specific issue.

I have a PHP page with a simplexml array that looks like the following, just longer:

    SimpleXMLElement Object 
    ( 
       [textID] => Array 
                ( 
                   [0] => SimpleXMLElement Object 
                       ( 
                          [textID] => 1 
                          [content] => Text1 
                       ) 
                   [1] => SimpleXMLElement Object 
                       ( 
                          [textID] => 2 
                          [content] => Text2
                       ) 
                   [2] => SimpleXMLElement Object 
                       ( 
                          [textID] => 3 
                          [content] => Text3 
                       ) 
                )
      )

Now I am trying to echo out a specific value from this array by referring to its ID which is an integer. The only way I get this working is the following but this just goes by the order within the array, not by the actual ID:

    <?php echo $objTexts->textID[1]->content; ?>

Can someone tell me what I am missing here ?

Thanks, Tim

Upvotes: 0

Views: 142

Answers (1)

IMSoP
IMSoP

Reputation: 97718

SimpleXML has no way of knowing that the textID identifies which node is which - it is just another element in the XML.

Based on your sample output, your XML is a little confusing as you have multiple elements called textID which each have a single child, also called textID, which has a different meaning. Nonetheless, what you want to do can be achieved either by looping through all the outer textID elements and testing the value of their inner textID element:

foreach ( $objTexts->textID as $item )
{
     if ( $item->textID == '2' )
     {
          ...
     }
}

Or, you could use XPath, which is a fairly simple query language for XML, and is supported within SimpleXML in the form of the ->xpath() method. In your case, you want to find a textID node which contains a textID child with a particular value, so the code would look something like this:

 // ->xpath always returns a plain PHP array - not a SimpleXML object
 $xpath_results = $objTexts->xpath('//textID[textID=2]');
 
 // If you're certain you only want the first result:
 echo $xpath_results[0]->content;
 
 // If you might want multiple matches
 foreach ( $xpath_results as $item )
 {
     ...
 }

Upvotes: 1

Related Questions