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

Wag*_*age 8 php xml parsing

我正在寻找一个解析器,它将允许我成功解析破碎的xml,采取"最好的猜测"方法 - 例如.

    <thingy>
       <description>
           something <b>with</b> bogus<br> 
           markup not wrapped in CDATA
       </description>
    </thingy>
Run Code Online (Sandbox Code Playgroud)

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

关于如何攻击问题的其他建议(除了有效标记开始)欢迎.

非PHP解决方案(例如Beautiful Soup(python))并不是面目全非,但我更愿意坚持公司的主流技能.

谢谢!

Car*_*rós 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);
Run Code Online (Sandbox Code Playgroud)

我试过这个脚本:

<?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";
}
Run Code Online (Sandbox Code Playgroud)

从 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$
Run Code Online (Sandbox Code Playgroud)

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

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