Note that "if (! $sxe) {" may give you a false-negative if the XML document was empty (e.g. "<root />"). In that case, $sxe will be:
object(SimpleXMLElement)#1 (0) {
}
which will evaluate to false, even though nothing technically went wrong.
Consider instead: "if ($sxe === false) {"
Lidiar con los errores XML
Lidiar con los errores XML cuando se cargan documentos es una tarea muy sencilla. Usando la funcionalidad libxml es posible suprimir todos los errores XML cuando se carga un documento y entonces, iterar sobre ellos.
El objeto libXMLError, retornado por libxml_get_errors(), contiene varias propiedades incluyendo el mensaje, línea y columna (posición) del error.
Ejemplo #1 Cargando un string XML erróneo
<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><roto><xml></roto>");
if ($sxe === false) {
echo "Error cargando XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>
El resultado del ejemplo sería:
Error cargando XML
Blank needed here
parsing XML declaration: '?>' expected
Opening and ending tag mismatch: xml line 1 and broken
Premature end of data in tag broken line 1
openbip at gmail dot com ¶
3 years ago
Jacob Tabak ¶
3 years ago
If you are trying to load an XML string with some escaped and some unescaped ampersands, you can pre-parse the string to ecsape the unescaped ampersands without modifying the already escaped ones:
<?php
$s = preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&'.substr('\\0',1))", $s);
?>
