[英]Forcing UTF8 Format with PHP's XMLReader, DOM and SimpleXML
我們有一個腳本來解析用戶生成的源中的XML提要,這些源有時會包含格式不正確的帶有特殊字符的條目。
雖然我通常只在行上運行utf8_encode(),但由於DOM逐漸讀取文件並且在執行expand命令時引發錯誤,因此我不確定如何執行此操作。
由於simple_xml對代碼造成阻塞,因此后續行也將關閉。
這是代碼。
$z = new XMLReader;
$z->open($filename); $doc = new DOMDocument('1.0','UTF-8');
while ($z->read() && $z->name !== 'product');
while ($z->nodeType == XMLReader::ELEMENT AND $z->name === 'product'){
$producti = simplexml_import_dom($doc->importNode($z->expand(), true));
print_r($producti);
}
錯誤:
消息:XMLReader :: expand():foo.xml:29081:解析器錯誤:輸入的UTF-8輸入不正確,表示編碼! 字節:0x05 0x20 0x2D 0x35
嚴重程度:警告
消息:XMLReader :: expand():擴展時發生錯誤
文件名:controllers / feeds.php
行號:106
消息:傳遞給DOMDocument :: importNode()的參數1必須是DOMNode的實例,給定為boolean
文件名:controllers / feeds.php
行號:106
首先使用HTML Tidy庫清除您的字符串。
另外,我最好使用DOMDocument而不是XMLReader。
像這樣:
$tidy = new Tidy;
$config = array(
'drop-font-tags' => true,
'drop-proprietary-attributes' => true,
'hide-comments' => true,
'indent' => true,
'logical-emphasis' => true,
'numeric-entities' => true,
'output-xhtml' => true,
'wrap' => 0
);
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
$xml = $tidy->value; // Get clear string
$dom = new DOMDocument;
$dom->loadXML($xml);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.