XML エラーの対応
ドキュメント読み込み時の XML エラーに対処するのは非常にシンプルな作業です。 libxml の機能を使うと、 ドキュメント読み込み時のすべての XML エラーを抑制して後からそれを処理することができます。
libxml_get_errors() が返す libXMLError オブジェクトには、エラーについての message や line、 column (場所) といったプロパティが含まれます。
例1 壊れた XML 文字列の読み込み
<?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
+add a note
User Contributed Notes 3 notes
openbip at gmail dot com ¶
14 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) {"
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
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 & without throwing warnings:
$str = preg_replace('/&(?!;{6})/', '&', $str);
You probably should have been doing this before /e was deprecated, actually.
↑ and ↓ to navigate •
Enter to select •
Esc to close
Press Enter without
selection to search using Google