2010-12-22 59 views
3

我有一個需要使用PHP加載的XML文檔。我目前使用simplexml_load_file()函數,但是xml文件格式不正確,因此我得到一個分析錯誤。在PHP中加載格式錯誤的XML

XML文件看起來是這樣的:

... 
</result>something1> 
</else> 
</else> 
</resu 
... 

正如你可以看到,這個XML是重擊而這個函數拋出試圖解析它的錯誤。此外,我不需要這些損壞的數據。我只想閱讀我能做的事情,並把其他所有事情都拋開。

+2

嘗試[DOM文檔:: loadHTML()](http://php.net/domdocument.loadhtml)。除此之外,除了手動完成之外,沒有別的選擇。 – Jonah 2010-12-22 23:14:35

回答

2

約拿布龍建議,嘗試的DOMDocument :: loadHTML():

$dom = new DOMDocument(); 
$dom->strictErrorChecking = false; 
libxml_use_internal_errors(true); 

$dom->loadHTML($xml); 
1

@Juliusz

你實際上並不需要爲這個我不認爲strictErrorChecking。我嘗試了以下,它似乎工作正常。要忽略您需要設置libxml_use_internal_errors(true)的錯誤。基本上你想使用DOMDocument而不是simplexml。我嘗試以下和工作沒有任何問題:

<?php 

$string = <<<XML 
<?xml version='1.0'?> 
<document> 
    <cmd>login</cmd> 
    <login>Richard</login> 

</else> 
</else> 
</document> 
XML; 

$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTML($string); 
print $dom->saveHTML(); 


?> 

Thusjanthan Kubendranathan