|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-12-03 22:26 UTC] toby at caboteria dot org
Description:
------------
There are at least two cases where the example code on the "Dealing with XML errors" page[0] won't work correctly. The first is mentioned in one of the notes[1]: a document with an empty root node will show up as an error, even if it parses correctly. The second is if the nodes just below the document node are in a different namespace.
I recommend using
if (libxml_get_errors()) {
instead of the existing code.
[0] http://php.net/manual/en/simplexml.examples-errors.php
[1] http://php.net/manual/en/simplexml.examples-errors.php#96416
Test script:
---------------
First case:
<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'?><not_broken/>");
if (!$sxe) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>
Second case:
<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'?><not_broken xmlns:m='urn:m'><m:foo></m:foo></not_broken>");
if (!$sxe) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>
Expected result:
----------------
Empty page.
Actual result:
--------------
Failed loading XML
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Dec 13 10:00:01 2025 UTC |
Not a bug. As that very same note indicates it's a false negative: there was no error. You just get an object that looks empty because you're doing a loose comparison and PHP defines an "empty" object as false. The SimpleXMLElement looks empty because the object is defined as containing all child nodes within a given namespace; in the first example there are no child nodes at all, and in the second example there are no child nodes in the default ("") namespace. That note and the one after both give you ways to work around the loose-typing issue: compare ===false or do a !($obj instanceof SimpleXMLElement).