Работа с ошибками XML

Работа с ошибками XML при загрузке документов является очень простой задачей. Использование функциональности libxml позволяет подавить все XML ошибки при загрузке документа и затем обработать их.

Объект libXMLError, возвращаемый libxml_get_errors(), содержит несколько свойств, в том числе сообщение, номер строки и колонку (позицию) этой ошибки.

Пример #1 Загрузка синтаксически неправильной XML строки

<?php
libxml_use_internal_errors
(true);
$sxe simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!
$sxe) {
    echo 
"Ошибка загрузки XML\n";
    foreach(
libxml_get_errors() as $error) {
        echo 
"\t"$error->message;
    }
}
?>

Результат выполнения данного примера:

Ошибка загрузки 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

Коментарии

Автор:
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' : '&amp;'.substr('\\0',1))"$s);
?>
2010-02-15 15:17:36
http://php5.kiev.ua/manual/ru/simplexml.examples-errors.html
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) {"
2010-02-25 22:20:17
http://php5.kiev.ua/manual/ru/simplexml.examples-errors.html
Автор:
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.
2014-09-12 00:29:00
http://php5.kiev.ua/manual/ru/simplexml.examples-errors.html
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.
class.domdocument#domdocument.props.recover
2015-09-04 17:21:39
http://php5.kiev.ua/manual/ru/simplexml.examples-errors.html

    Поддержать сайт на родительском проекте КГБ