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>
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Rather than using getNamespaces, you can pass true to ->attributes(): echo $k->attributes('xsi', true)->type.
The solution by IMSoP works great! And it's more direct than mine, totally the final solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.