PHP 8.5.0 Alpha 1 available for testing

Manejo de errores XML

El manejo de errores XML al cargar un documento es una tarea sencilla. Utilizando las funcionalidades libxml, es posible suprimir todos los errores XML al cargar un documento, y luego recorrerlos.

El objeto libXMLError, devuelto por la función libxml_get_errors(), contiene varias propiedades como el mensaje, la línea y la columna (posición) del error.

Ejemplo #1 Carga de cadenas XML rotas

<?php
libxml_use_internal_errors
(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (
$sxe === false) {
echo
"Error al cargar el XML\n";
foreach(
libxml_get_errors() as $error) {
echo
"\t", $error->message;
}
}
?>

El resultado del ejemplo sería:

Error al cargar el 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

add a note

User Contributed Notes 3 notes

up
21
openbip at gmail dot com
15 years ago
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) {"
up
2
1337 at netapp dot com
9 years ago
If you need to process the content of your broken XML-doc you might find this interesting. It has blown past a few simple corruptions for me.
http://php.net/manual/en/class.domdocument.php#domdocument.props.recover
up
4
tuxedobob
10 years ago
Now that the /e modifier is considered deprecated in preg_replace, you can use a negative lookahead to replace unescaped ampersands with &amp; without throwing warnings:

$str = preg_replace('/&(?!;{6})/', '&amp;', $str);

You probably should have been doing this before /e was deprecated, actually.
To Top