PHP XMLReader偶然发现无效字符并停止


PHP XMLReader stumbles upon invalid character and stops

正如标题所说。

我正在处理大量下载的XML文件。其中一些文件包含无效字符,如"US"或"VB"(垂直选项卡)。不知道为什么这些角色一开始就在那里。我真的对他们无能为力。

$z = new XMLReader;
$z->open('compress.zlib://'.$file, "UTF-8");
while ($z->read() && $z->name !== 'p');
while ($z->name === 'p'){
try
{
    $node = new SimpleXMLElement($z->readOuterXML());
}catch(Exception $e)
{
    echo $e->getMessage();
}
// And so on
}

我收到一个错误,说"字符串无法解析为XML"。

我在这里能做什么?

最终找到了解决方案。

我决定用fopen来构建&动态过程。以下是我最终得到的:

$handle = fopen('compress.zlib://'.$file, 'r');
$xml_source = '';
$record = false;
if($handle){
    while(($buffer = fgets($handle, 4096)) !== false){
        if(strpos($buffer, '<open_tag>') > -1){
            $xml_source = '<?xml version="1.0" encoding="UTF-8"?>';
            $record = true;
        }
        if(strpos($buffer, '</close_tag') > -1){
            $xml_source .= $buffer;
            $record = false;
            $xml = simplexml_load_string(stripInvalidXml($xml_source));
            // ... do stuff here with the xml element
        }
        if($record){
            $xml_source .= $buffer;
        }
    }
}

函数simplexml_load_string()是提供的一个quickshiftin。工作起来很有魅力。