开发者

Avoid DOMDocument XML warnings in php

开发者 https://www.devze.com 2023-03-28 17:42 出处:网络
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:

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 d开发者_如何学运维elete the file?


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.

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 solution makes it less strict, but it'll still issue warnings for some of the errors:
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
  • DON'T do what Fran Verona suggested - globally disabling error reporting is something you should never do. In production, set your own error handler and display a prettier message to the user, and make sure the error is logged somewhere - but never disable it completely. Setting error_reporting to 0 will cause PHP to disable error logging too.
  • Xeon06 solution is problematic because you're effecting the entire script error handler for a specific piece of code. Using your own error handler that simply ignores the error causes the same issues as Fran's solution.


Use set_error_handler.

set_error_handler("yourHandler", E_WARNING);


Turn off strict error checking:

$dom = new DOMDocument();
$dom->strictErrorChecking = FALSE ;

$dom->load('/path/to/file.xml');
if (!$dom->validate()) {
   // Invalid XML!
}
0

精彩评论

暂无评论...
验证码 换一张
取 消