Search code examples
phpsimplexml

PHP - SimpleXMLElement - How to Access this element


I'm trying to access a element in my SimpleXMLElement "array".

My XML looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <changeinfo>
      <changes app_ver="01.16">
        <![CDATA[
          Minor interface changes
          
          Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.
        ]]>
      </changes>
      <changes app_ver="01.15">
        <![CDATA[
          WBPlay unlockables no longer requires WBPlay
        ]]>
      </changes>
      <changes app_ver="01.14">
        <![CDATA[
          General Game Play and Balance Tweaks
          
          Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.
        ]]>
      </changes>
    </changeinfo>

Loading it with simplexml_load_string() gives me the following var_dump result:

object(SimpleXMLElement)#40 (1) {
  ["changes"]=>
  array(16) {
    [0]=>
    object(SimpleXMLElement)#39 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.16"
      }
    }
    [1]=>
    object(SimpleXMLElement)#41 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.15"
      }
    }
    [2]=>
    object(SimpleXMLElement)#42 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.14"
      }
  }
}

How can I access a changes entry that I want the content of?

For example, how can I do:

echo $xml->changes['01.16'];

expecting it to output the first entry content (Minor interface changes ...)?


Solution

  • Try something like:

    $string = <<<XML
    [your xml above]
    XML;
    
    $xml = simplexml_load_string($string);
    $results = $xml->xpath('.//changes[@app_ver="01.16"]'); 
    echo (trim($results[0]));
    

    Output:

    Minor interface changes
              
              Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.