Search code examples
phpxmlsimplexml

Read xml element with simpleXML in php with name which contain :


I'm using SimpleXML in PHP and I tried to parse xml file which contain : in element name, like this:

<url>
  <url1> url </url>
  <data:data> some data </data:data>
</url>  

main problem is I can't parse element whith such name ( <data:data> ), I tried $xml->url->{'data:data'}; but I got no effect. When I tried to find out all <ulr> childred with

foreach ($url->children() as $key ) {
                 echo $key->getName() ;
    }

I got only one child, can anyone help me how to parse xml whith : in name. I tried change <data:data> to <data-data> then {'data-data'} worked, but this insnt solution for me


Solution

  • A name that contains ":" in XML is considered a namespace which needs to be defined.

    Straight from the docs of SimpleXMLElement::children example #2.

    $xml = '<example xmlns:foo="my.foo.urn">
      <foo:a>Apple</foo:a>
      <foo:b>Banana</foo:b>
      <c>Cherry</c>
    </example>';
    
    $sxe = new SimpleXMLElement($xml);
    
    $kids = $sxe->children('foo');
    var_dump(count($kids));