How to parse an XML ignoring errors with SimpleXML

 ̄綄美尐妖づ 提交于 2019-12-01 13:21:18
Baba

From PHP DOC simplexml_load_file options should be int not array

Replace

$xml = simplexml_load_file($url, "SimpleXMLElement", array(LIBXML_NOERROR, LIBXML_ERR_NONE));
                                                       ^------- You are using array

With

$xml = simplexml_load_file($url, "SimpleXMLElement", LIBXML_NOERROR |  LIBXML_ERR_NONE);

Instead of suppressing this errors you can as well fix the xml with Tidy package.

Example bad.xml

<Family>
    <name>Hankre</name>
    <adults>2</adults>
    <kids > 16 </kids>
    <food>
        <tag>Nice </tag>
        <tag>Food </tag>
        <tag />

Fix 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;

Output

<Family>
    <name>Hankre</name>
    <adults>2</adults>
    <kids>16</kids>
    <food>
        <tag>Nice</tag>
        <tag>Food</tag>
        <tag />
    </food>
</Family>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!