Loading an XML file with simplexml_load_file() and then echoing it with print_r($xml) can leave you wondering why it appears empty:
<code class="xml"><ArrayOfItem> <Item> <attributes> <Attribute> <dataType>string</dataType> </Attribute> </attributes> </Item> </ArrayOfItem></code>
<code class="php">$xml = simplexml_load_file('myfile.xml'); print_r($xml);</code>
Result:
SimpleXMLElement Object ( [Item] => SimpleXMLElement Object ( ) )
Why is this empty?
The reason for this is that print_r() doesn't output the contents of the elements in the
Solution:
To access and output the contents of those elements, use methods specifically designed to handle XML namespaces, such as SimpleXMLElement::children() or SimpleXMLElement::xpath(). For example:
<code class="php">// Get children with namespace 'q1' $children = $xml->Item->children('q1', true); // Loop through and output child nodes foreach ($children as $child) { echo 'Child node: ' . $child->getName() . ' value: ' . $child->dataType . "\n"; }</code>
The above is the detailed content of Why is my SimpleXML Object Empty When Using print_r() on an XML File with Namespaces?. For more information, please follow other related articles on the PHP Chinese website!