如何使用 SimpleXML 解析 XML 忽略错误 [英] How to parse an XML ignoring errors with SimpleXML
本文介绍了如何使用 SimpleXML 解析 XML 忽略错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 .xml 文档经常包含错误.无论如何,我想解析我的文档直到出现错误或尝试自动修复错误.那可能吗?
Often my .xml document contains errors. I would want to parse my document anyway up to errors or try to fix errors automatically. Is that possible?
我已经试过了,但它不起作用
I have tried this, but it isn't working
$xml = simplexml_load_file($url, "SimpleXMLElement", array(LIBXML_NOERROR, LIBXML_ERR_NONE));
if (!$xml) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
推荐答案
来自 PHP DOC simplexml_load_file 选项应该是 int 而不是数组
From PHP DOC simplexml_load_file options should be int not array
替换
$xml = simplexml_load_file($url, "SimpleXMLElement", array(LIBXML_NOERROR, LIBXML_ERR_NONE));
^------- You are using array
与
$xml = simplexml_load_file($url, "SimpleXMLElement", LIBXML_NOERROR | LIBXML_ERR_NONE);
您也可以使用 Tidy 包.
示例 bad.xml
<Family>
<name>Hankre</name>
<adults>2</adults>
<kids > 16 </kids>
<food>
<tag>Nice </tag>
<tag>Food </tag>
<tag />
修复 XML
$config = array(
'indent' => true,
'clean' => true,
'input-xml' => true,
'output-xml' => true,
'wrap' => false
);
$tidy = new Tidy();
$xml = $tidy->repairfile($badXML, $config);
echo $xml;
输出
<Family>
<name>Hankre</name>
<adults>2</adults>
<kids>16</kids>
<food>
<tag>Nice</tag>
<tag>Food</tag>
<tag />
</food>
</Family>
这篇关于如何使用 SimpleXML 解析 XML 忽略错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文