小编典典

在通过DomDocument(PHP)加载格式不正确的HTML时禁用警告

html

我需要解析一些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)

可以禁止显示警告,但是如何以编程方式捕获这些警告?


阅读 174

收藏
2020-05-10

共1个答案

小编典典

您可以使用安装临时错误处理程序 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());
}
2020-05-10