2

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>
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Federinik
  • 523
  • 4
  • 20
  • Take a look at this: http://www.php.net/manual/en/class.simplexmliterator.php, there's `getChildren()`. – EM-Creations Jun 06 '13 at 14:24
  • possible duplicate of [How to get attribute of node with namespace using SimpleXML?](http://stackoverflow.com/questions/6576773/how-to-get-attribute-of-node-with-namespace-using-simplexml) - You are accessing an attribute of a node in a different namespace. – hakre Jun 06 '13 at 14:33

1 Answers1

6

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.

Federinik
  • 523
  • 4
  • 20
  • 6
    Rather than using `getNamespaces`, you can pass `true` to `->attributes()`: `echo $k->attributes('xsi', true)->type`. – IMSoP Jun 06 '13 at 17:43
  • The solution by IMSoP works great! And it's more direct than mine, totally the final solution. – Federinik Jun 07 '13 at 16:12