DomDocument(PHP)加载非格式良好的HTML时禁用警告 [英] Disable warnings when loading non-well-formed HTML by DomDocument (PHP)

查看:81
本文介绍了DomDocument(PHP)加载非格式良好的HTML时禁用警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一些HTML文件,但是它们格式不正确,PHP会输出警告。我想以编程方式避免这种调试/警告行为。请指教。

代码:

  //创建一个DOM文档并加载HTML数据
$ xmlDoc = new DomDocument;
//这会抛出警告
$ xmlDoc-> loadHTML($ fetchResult);

这:

  @ $ xmlDoc-> loadHTML($ fetchResult)

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

解决方案

您可以使用 set_error_handler

  class ErrorTrap {
protected $ callback;
protected $ errors = array();
函数__construct($ callback){
$ this-> callback = $ callback;
}
函数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();
抛出$ ex;
}
restore_error_handler();
返回$ result;
}
函数onError($ errno,$ errstr,$ errfile,$ errline){
$ this-> errors [] = array($ errno,$ errstr,$ errfile,$ errline);
}
函数ok(){
return count($ this-> errors)=== 0;
}
函数错误(){
return $ this-> errors;


$ / code $ / pre

用法:

  //创建DOM文档并加载HTML数据
$ xmlDoc = new DomDocument();
$ caller = new ErrorTrap(array($ xmlDoc,'loadHTML'));
//这不会抛出任何警告
$ caller-> call($ fetchResult);
if(!$ caller-> ok()){
var_dump($ caller-> errors());
}


I need to parse some HTML files, however, they are not well-formed and PHP prints out warnings to. I want to avoid such debugging/warning behavior programatically. Please advise. Thank you!

Code:

// create a DOM document and load the HTML data
$xmlDoc = new DomDocument;
// this dumps out the warnings
$xmlDoc->loadHTML($fetchResult);

This:

@$xmlDoc->loadHTML($fetchResult)

can suppress the warnings but how can I capture those warnings programatically?

解决方案

You can install a temporary error handler with 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;
  }
}

Usage:

// 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());
}

这篇关于DomDocument(PHP)加载非格式良好的HTML时禁用警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆