避免PHP中的DOMDocument XML警告

避免PHP中的DOMDocument XML警告

问题描述:

我正在从服务器中获取xml文件,有时会收到无效的xml文件,因此,我收到警告:

I'm fetching xml files from a server and sometimes I'm getting a non-valid xml files, because of this I'm getting a warning:

Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in 

如何捕获此警告并删除文件?

How can I catch this warning and delete the file?

您有两种选择.在load()调用中使用@错误控制运算符,例如@$dom->load()有点慢,因为它会全局将display_errors的值更改为off,然后执行该函数并将其重新设置为on.

You have two choices. Either use the @ error control operator in your load() call, e.g. @$dom->load(), which is somewhat slow because it globally changes the value of display_errors to off, executes the function and sets it back to on.

我个人更喜欢的另一种选择(我讨厌@运算符,我不能忍受在我的代码中看到它)是保存libxml_use_internal_errors ,使用libxml_use_internal_errors(TRUE)启用它,调用该函数,清除错误缓冲区并恢复旧值.这是我的代码中的一个片段,用于执行此操作:

The other option, which I personally prefer (I hate the @ operator, I can't stand to see it in my code) is to save the old value of libxml_use_internal_errors, enable it using libxml_use_internal_errors(TRUE), call the function, clear the errors buffer and restore the old value. Here's a snippet from my code that does that:

<?php
$previous_value = libxml_use_internal_errors(TRUE);
$doc->loadHTML((string)$e->response->getBody());
libxml_clear_errors();
libxml_use_internal_errors($previous_value);

我还不能对答案发表评论,所以我在这里写下:

I can't comment on answers yet, so I'll write it here:

  • Michael解决方案的严格程度有所降低,但仍会针对某些错误发出警告:

nadav@shesek:~$ php -r '$dom=new DOMDocument; $dom->strictErrorChecking = FALSE ; $dom->loadHTML("<xy></zx>");'
PHP Warning:  DOMDocument::loadHTML(): Tag xy invalid in Entity, line: 1 in Command line code on line 1

  • 请勿执行Fran Verona的建议-全局禁用错误报告是您永远不应该做的事情.在生产环境中,设置您自己的错误处理程序并向用户显示更漂亮的消息,并确保将错误记录在某处-但切勿完全禁用它.将error_reporting设置为0也会导致PHP也禁用错误日志记录.
  • Xeon06解决方案存在问题,因为您正在影响特定代码段的整个脚本错误处理程序.使用仅忽略错误的错误处理程序会导致与Fran的解决方案相同的问题.