我需要解析一些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)
我可以抑制警告,但我如何才能以编程方式捕获这些警告呢?
发布于 2009-07-19 00:39:40
可以使用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());
}
发布于 2010-05-17 14:54:29
打电话
libxml_use_internal_errors(true);
在使用$xmlDoc->loadHTML()
进行处理之前
这会将libxml2 not to send错误和警告告知PHP。然后,为了检查错误并自己处理它们,您可以在准备好时咨询libxml_get_last_error()和/或libxml_get_errors():
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$errors = libxml_get_errors();
foreach ($errors as $error) {
// handle the errors as you wish
}
发布于 2018-08-03 14:50:31
设置选项"LIBXML_NOWARNING“和"LIBXML_NOERROR”也可以很好地工作:
$dom->loadHTML($html, LIBXML_NOWARNING | LIBXML_NOERROR);
https://stackoverflow.com/questions/1148928
复制相似问题