2011-05-07 109 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