PHP 8.5.8 Released!

Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The LibXMLError object, returned by libxml_get_errors() , contains several properties including the message, line and column (position) of the error.

示例 #1 Loading broken XML string

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

以上示例会输出:

Failed loading 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

参见

发现了问题?

了解如何改进此页面提交拉取请求报告一个错误
+添加备注

用户贡献的备注 3 notes

up
21
openbip at gmail dot com
16 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
3
1337 at netapp dot com
10 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
11 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.
+添加备注

AltStyle によって変換されたページ (->オリジナル) /