2013-02-25 60 views
-1

我已經從curl請求中收到這個XML。忽略XML之外的無效char?

<?xml version="1.0" encoding="utf-8"?> 
<transaction> 
    <result>PENDING</result> 
    <merchanttransid>343434343</merchanttransid> 
    <transref>23232323</transref> 
    <errorcode>000</errorcode> 
    <errormessage/> 
    <description/> 
</transaction> 
SMTP Error: Could not connect to SMTP host. 

但是,服務器正在回覆SMTP的附加錯誤響應錯誤:無法連接到SMTP主機。現在,當通過simplexml_load_string()解析時。

它拋出一個錯誤:

Entity: line 10: parser error: Extra content at the end of the document (Error Number: 2)

由於中,XML是正確的,只是對響應的問題,有沒有對如何帶額外線的方法嗎?

+1

最好的解決方案是讓服務的創建者修復它。 – CodeZombie 2013-02-25 08:26:51

+0

XML不正確。這也是爲什麼SimpleXML在這裏給出錯誤的原因。如果你想加載它,你需要使用姊妹庫* DOMDocument *並將恢復設置爲true。請參閱[此答案於*「在使用DOMDocument函數處理之前在PHP中修復格式不正確的XML」*](http://stackoverflow.com/a/9281963/367456)。 – hakre 2013-05-10 21:58:43

回答

0

你可以嘗試調用函數傳遞參數忽略讀取XML的錯誤信息:

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

您可以查看完整列表的選項,你可以通過這個功能:http://www.php.net/manual/en/libxml.constants.php

另一種解決方案(如果你想解析大文件,這不太好)是逐行讀取字符,然後刪除最後一行。

$xml = '<?xml...?>'; 
$lines = explode("\n", $xml); 
unset($lines[count($lines)-1]); // remove last line 
$output = implode($lines); // output now contains xml without the last line 

希望有所幫助。

+0

即使沒有錯誤,第二個示例也會刪除最後一行。 – Voitcus 2013-02-26 08:56:44

+0

是的,那麼我們可以把你的解決方案與這個結合起來,只需簡單地檢查一下,確保最後一行沒有任何開放標籤。 :-) – vitozev 2013-02-27 08:46:57

0

如果您知道結構將始終如此,請爲每一行循環,從左側剝離空白,並且如果第一個字符與「<」不同,則刪除該行。最後給SimpleXML結果。