Search code examples
phpxsdsimplexml

PHP SimpleXML: handling XSD schema tags


I use foreach($node->children() as $childNode) to loop all childs for node. It works fine when child nodes is like <nodename>content</nodename>.

When node is like:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.w3schools.com"
xmlns="https://www.w3schools.com"
elementFormDefault="qualified">
</xs:schema>

it doesn't work. This nodes as if ignored in foreach.

My file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root attr1="asasasa" attr2="dscd">
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.w3schools.com"
xmlns="https://www.w3schools.com"
elementFormDefault="qualified">
</xs:schema>
  <Params>
    <node>content</node>
    <newnode>content 2</newnode>
  </Params>
</root>

Code:

$node = simplexml_load_file($path, 'SimpleXMLElement', LIBXML_NOCDATA);

foreach($node->children() as $childNode) { ... }

On the first iteration of loop - $childNode is , but I need first

How to solve this problem?

Thank you.


Solution

  • There are two namespaces in the document. So I'm assuming you have to do it twice:

    foreach($node->children("http://www.w3.org/2001/XMLSchema") as $childNode) {
        var_dump($childNode);
    }
    foreach($node->children() as $childNode) {
        var_dump($childNode);
    }
    

    or you could use xpath:

    foreach ($node->xpath ("/root/*") as $n)
    {
        var_dump ($n);
    }
    

    or with all the attributes:

    foreach ($node->xpath ("./*") as $n)
    {
        var_dump ($n);
        var_dump ($n->getNamespaces());
    }