title: Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
body: <p>This question is intended as a reference to answer a particularly common question, which might take different forms:</p>
  <ul>
  <li>I have an XML document which contains multiple namespaces; how do I parse it with SimpleXML?</li>
  <li>My XML has a colon (&quot;:&quot;) in the tag name, how do I access it with SimpleXML?</li>
  <li>How do I access attributes in my XML file when they have a colon in their name?</li>
  </ul>
  <p>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.</p>
  <p>Here is an illustrative example:</p>
  <pre><code>$xml = 
      &lt;&lt;&lt;XML
      &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
      &lt;document xmlns=&quot;http://example.com&quot; xmlns:ns2=&quot;https://namespaces.example.org/two&quot; xmlns:seq=&quot;urn:example:sequences&quot;&gt;
          &lt;list type=&quot;short&quot;&gt;
              &lt;ns2:item seq:position=&quot;1&quot;&gt;A thing&lt;/ns2:item&gt;
              &lt;ns2:item seq:position=&quot;2&quot;&gt;Another thing&lt;/ns2:item&gt;
          &lt;/list&gt;
      &lt;/document&gt;
      XML;
  $sx = simplexml_load_string($xml);
  </code></pre>
  <p>This code <strong>will not work</strong>; why not?</p>
  <pre><code>foreach ( $sx-&gt;list-&gt;ns2:item as $item ) {
      echo 'Position: ' . $item['seq:position'] . &quot;\n&quot;;
      echo 'Item: ' . (string)$item . &quot;\n&quot;;
  }
  </code></pre>
  <p>The first problem is that <code>-&gt;ns2:item</code> is invalid syntax; but changing it to this <strong>doesn't work either</strong>:</p>
  <pre><code>foreach ( $sx-&gt;list-&gt;{'ns2:item'} as $item ) { ... }
  </code></pre>
  <p><strong>Why not, and what should you use instead?</strong></p>