Federinik
Federinik

Reputation: 521

Access attributes of XML node with namespace in PHP

I have something like this:

$x = simplexml_load_file('myxml.xml');

[...]

foreach($x->y->z[0]->w->k as $k){
    [...]
}

My XML file is something like:

<x>
  <y>
    <z>
      <w>
        <k prefix:name="value">
          [...]
        </k>
      </w>
      [...]
    </z>
    [...]
  </y>
  [...]
</x>

Now, I'd like to access an attribute of my k element. I have red that I can access it using, in my foreach:

$k['prefix:name']

But it doesn't work. What I'm I doing wrong?

I added a fake attribute to my k element and it worked, I think the problem is that the attribute I'm trying to access is in a different namespace:

<k xsi:type="value">
[...]
</k>

Upvotes: 2

Views: 2196

Answers (1)

Federinik
Federinik

Reputation: 521

I solved it, I found the solution at http://bytes.com/topic/php/answers/798486-simplexml-how-get-attributes-namespace-xml-vs-preg_

foreach($x->y->z[0]->w->k as $k){                 
  $namespaces = $k->getNameSpaces(true);                 
  $xsi = $k->attributes($namespaces['xsi']);

  echo $xsi['type']; 
}

The getNameSpaces(true) function returns the namespaces of the XML document, then I select the one I'm looking for (xsi) and access the attribute I need like if the attributes is of the namespaces, and not of the $k node. I wish this can help someone else.

Upvotes: 6

Related Questions