Search code examples
phpxmlsimplexml

PHP - Unable to parse attribute using SimpleXML


Given the following xml:

 <data xmlns:ns2="...">
     <versions>
            <ns2:version type="HW">E</ns2:version>
            <ns2:version type="FW">3160</ns2:version>
            <ns2:version type="SW">3.4.1 (777)</ns2:version>
     </versions>
    ...
 </data>

I am trying to parse the third attribute ~ns2:version type="SW" but when running the following code I get nothing..

$s = simplexml_load_file('data.xml');

echo $s->versions[2]->{'ns2:version'};

Running this gives the following output:

$s = simplexml_load_file('data.xml');

var_dump($s->versions);

enter image description here

How can I properly get that attribute?


Solution

  • You've got some quite annoying XML to work with there, at least as far as SimpleXML is concerned.

    Your version elements are in the ns2 namespace, so in order to loop over them, you need to do something like this:

    $s = simplexml_load_string($xml);
    
    foreach ($s->versions[0]->children('ns2', true)->version as $child) {
      ...
    }
    

    The children() method returns all children of the current tag, but only in the default namespace. If you want to access elements in other namespaces, you can pass the local alias and the second argument true.

    The more complicated part is that the type attributes is not considered to be part of this same namespace. This means you can't use the standard $element['attribute'] form to access it, since your element and attribute are in different namespaces.

    Fortunately, SimpleXML's attributes() method works in the same way as children(), and so to access the attributes in the global namespace, you can pass it an empty string:

    $element->attributes('')->type
    

    In full, this is:

    $s = simplexml_load_string($xml);
    
    foreach ($s->versions[0]->children('ns2', true)->version as $child) {
      echo (string) $child->attributes()->type, PHP_EOL;
    }
    

    This will get you the output

    HW
    FW
    SW