David David - 1 year ago 70
PHP Question

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:

<Attributes xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">

My current code:

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

Any guidance would be appreciated.


Answer Source

You need to register the namespace:

foreach ($xml->xpath('//Attributes') as $attr) {
  foreach ($attr->xpath('//ns:string') as $string) {
    echo $string, PHP_EOL;

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

foreach ($xml->xpath('//Attributes/ns:string') as $string) {
  echo $string, PHP_EOL;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download