PHP是否存在宽松,宽松的XML解析器?

时间:2011-05-17 13:31:56

标签: php xml parsing

我正在寻找一个解析器,它允许我成功解析破碎的xml,采用“最佳猜测”方法 - 例如。

    <thingy>
       <description>
           something <b>with</b> bogus<br> 
           markup not wrapped in CDATA
       </description>
    </thingy>

理想情况下,它会产生一个东西,具有描述属性和内部的任何标记汤。

有关如何解决问题的其他建议(除了开始使用有效标记)欢迎。

非php解决方案(例如美丽的汤(python))并不是苍白的,但我更愿意坚持公司的主流技能

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用DOMDocument::loadHTML()(或DOMDocument::loadhtmlfile())将损坏的XML转换为正确的XML。如果您不喜欢处理DOMDocument个对象,请使用saveXML()并使用SimpleXML加载生成的XML字符串。

$dom = DOMDocument::loadHTMLfile($filepath);
if (!$dom)
{
    throw new Exception("Could not load the lax XML file");
}
// Now you can work with your XML file using the $dom object.


// If you'd like using SimpleXML, do the following steps.
$xml = new SimpleXML($dom->saveXML());
unset($dom);

我试过这个剧本:

<?php
$dom = new DOMDocument();
$dom->loadHTMLFile('badformatted.xml');
if (!$dom)
{
    die('error');
}
$nodes = $dom->getElementsByTagName('description');
for ($i = 0; $i < $nodes->length; $i++)
{
    echo "Node content: ".$nodes->item($i)->textContent."\n";
}

从CLI执行此操作时的输出:

carlos@marmolada:~/xml$ php test.php

Warning: DOMDocument::loadHTMLFile(): Tag thingy invalid in badformatted.xml, line: 1 in /home/carlos/xml/test.php on line 3

Warning: DOMDocument::loadHTMLFile(): Tag description invalid in badformatted.xml, line: 2 in /home/carlos/xml/test.php on line 3
Node content:
                something with bogus
                markup not wrapped in CDATA

carlos@marmolada:~/xml$

编辑:一些小的修正和错误处理。

edit2:更改为非静态调用以避免E_STRICT错误,添加了测试用例。

答案 1 :(得分:1)

另一种方法是使用Tidy HTML库(PHP binding here)来首先清理HTML。它存在相当多的相当可怕的输入,我看到人们之前使用它来抓取相当松散的HTML。

相关问题