Search code examples
phpxmlxpathsimplexmlxml-namespaces

Retrieving an array of values from an XML content with a namespace in PHP


I'm having some issues retrieving the tag values of an XML feed which has a namespace.

I've read and tried to implement some of the recommended answers on previous questions, but I still get an empty array, or a warning like

Warning: SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix

I read Parse XML with Namespace using SimpleXML.

The XML feed data looks like this:

<Session>
      <AreComplimentariesAllowed>true</AreComplimentariesAllowed>
      <Attributes xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
         <d3p1:string>0000000009</d3p1:string>
         <d3p1:string>0000000011</d3p1:string>
      </Attributes>
</Session>

My current code:

foreach($xml->Session as $event){
    if(!empty($event->Attributes)){
        foreach($event->xpath('//Attributes:d3p1') as $atts) {
             echo $atts."<br />";
        }
    }
}

Any guidance would be appreciated.

Thanks.


Solution

  • You need to register the namespace:

    foreach ($xml->xpath('//Attributes') as $attr) {
      $attr->registerXPathNamespace('ns',
        'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
      foreach ($attr->xpath('//ns:string') as $string) {
        echo $string, PHP_EOL;
      }
    }
    

    In case if you want to fetch only the values of string tags:

    $xml->registerXPathNamespace('ns',
      'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
    foreach ($xml->xpath('//Attributes/ns:string') as $string) {
      echo $string, PHP_EOL;
    }