我需要解析一些HTML文件,但是它们的格式不正确,PHP向其输出警告。我想以编程方式避免这种调试/警告行为。请指教。谢谢!
码:
// create a DOM document and load the HTML data $xmlDoc = new DomDocument; // this dumps out the warnings $xmlDoc->loadHTML($fetchResult);
这个:
@$xmlDoc->loadHTML($fetchResult)
可以禁止显示警告,但是如何以编程方式捕获这些警告?
您可以使用安装临时错误处理程序 set_error_handler
set_error_handler
class ErrorTrap { protected $callback; protected $errors = array(); function __construct($callback) { $this->callback = $callback; } function call() { $result = null; set_error_handler(array($this, 'onError')); try { $result = call_user_func_array($this->callback, func_get_args()); } catch (Exception $ex) { restore_error_handler(); throw $ex; } restore_error_handler(); return $result; } function onError($errno, $errstr, $errfile, $errline) { $this->errors[] = array($errno, $errstr, $errfile, $errline); } function ok() { return count($this->errors) === 0; } function errors() { return $this->errors; } }
用法:
// create a DOM document and load the HTML data $xmlDoc = new DomDocument(); $caller = new ErrorTrap(array($xmlDoc, 'loadHTML')); // this doesn't dump out any warnings $caller->call($fetchResult); if (!$caller->ok()) { var_dump($caller->errors()); }