This question is intended as a reference to answer a particularly common question, which might take different forms:
- I have an XML document which contains multiple namespaces; how do I parse it with SimpleXML?
- My XML has a colon (":") in the tag name, how do I access it with SimpleXML?
- How do I access attributes in my XML file when they have a colon in their name?
If your question has been closed as a duplicate of this, it may not be identical to these examples, but this page should tell you what you need to know.
Here is an illustrative example:
$xml =
<<<XML
<?xml version="1.0" encoding="utf-8"?>
<document xmlns="http://example.com" xmlns:ns2="https://namespaces.example.org/two" xmlns:seq="urn:example:sequences">
<list type="short">
<ns2:item seq:position="1">A thing</ns2:item>
<ns2:item seq:position="2">Another thing</ns2:item>
</list>
</document>
XML;
$sx = simplexml_load_string($xml);
This code will not work; why not?
foreach ( $sx->list->ns2:item as $item ) {
echo 'Position: ' . $item['seq:position'] . "\n";
echo 'Item: ' . (string)$item . "\n";
}
The first problem is that ->ns2:item is invalid syntax; but changing it to this doesn't work either:
foreach ( $sx->list->{'ns2:item'} as $item ) { ... }
Why not, and what should you use instead?