2011-05-07 111 views
2

我正在使用PEAR XML_Feed_Parser。 我有一些bad xml,我給它,並得到錯誤。loadXML無法解決的錯誤

DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding ! 
Bytes: 0xE8 0xCF 0xD3 0xD4 in Entity, line: 7 

它實際上是錯誤編碼的html - KOI8-R。

可以得到錯誤,但我無法處理它!

當我創建新的XML_Feed_Parser實例與 $ feed = new XML_Feed_Parser($ xml);

它調用__construct(),它看起來像

$this->model = new DOMDocument; 
if (! $this->model->loadXML($feed)) { 
    if (extension_loaded('tidy') && $tidy) { 
     /* tidy stuff */ 
     } 
    } else { 
     throw new Exception('Invalid input: this is not valid XML'); 
} 

在哪裏,我們可以看到,如果loadXML的(),那麼它失敗,拋出異常。

我想從loadXML()中捕獲錯誤以跳過錯誤的XML並通知用戶。所以,我包我的代碼的try-catch像

try 
{ 
    $feed = new XML_Feed_Parser($xml); 
    /* ... */ 
} 
catch(Exception $e) 
{ 
    echo 'Feed invalid: '.$e->getMessage(); 
    return False; 
} 

但即使在那之後我得到這個錯誤

DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding ! 
Bytes: 0xE8 0xCF 0xD3 0xD4 in Entity, line: 7 

我讀過有關的loadXML(),發現

如果將空字符串作爲源傳遞,則會生成警告。此警告不是由libxml生成的,並且不能使用libxml的錯誤處理函數來處理。

但不知何故,而不是警告我得到錯誤,停止我的應用程序。我寫了我的錯誤處理程序,我看到這是真正的警告($ errno是2)。

所以我看到2個解決方案:

  1. 還原警告警告 - 不要 像對待錯誤。 (谷歌 不幫我在這裏)。之後 句柄False從loadXML返回。

  2. 以某種方式捕獲該錯誤。

任何幫助?

+0

重複? http://stackoverflow.com/questions/2507608/error-input-is-not-proper-utf-8-indicate-encoding-using-phps-simplexml-loa – 2011-05-07 19:18:00

+0

@ marek-sebera有點重複。我試圖用iconv進行轉換。但mb_detect_encoding沒有檢測到編碼:-)它告訴我,我的不良xml是UTF-8,這顯然不是真的(它是KOI8-R) – 2011-05-07 19:35:37

+0

有趣。當我在控制檯中啓動帶有xml文件的loadXML時,它給了我警告,我無法從中捕獲到False。也許這是錯誤的Apache? – 2011-05-07 20:13:45

回答

3

libxml_use_internal_errors(true)解決我的問題。它使libxml使用正常的錯誤,所以我可以從loadXML()捕獲False。

0

試試這個:

$this->model = new DOMDocument; 
$converted = mb_convert_encoding($feed, 'UTF-8', 'KOI8-R'); 
if (! $this->model->loadXML($converted)) { 
if (extension_loaded('tidy') && $tidy) { 
    /* tidy stuff */ 
    } 
} else { 
    throw new Exception('Invalid input: this is not valid XML'); 
} 

,或者你可以做到這一點,而不需要修改XML_Feed_Parser這樣的:

$xml = mb_convert_encoding($loaded_xml, 'UTF-8', 'KOI8-R'); 
$feed = new XML_Feed_Parser($xml); 
+0

不起作用。此外,它破壞了我的優秀XML以UTF-8格式轉換爲亂碼。 – 2011-05-07 20:37:14

+0

是的,它不是用來轉換UTF8-> UTF8只是爲了這種情況,所以也許你應該爲此添加一些例外,在feed設置中有一些選項。 – 2011-05-07 21:05:59