Vie*_*iet 74 html php warnings domdocument
我需要解析一些HTML文件,但是,它们格式不正确并且PHP打印出警告.我想以编程方式避免这种调试/警告行为.请指教.谢谢!
码:
// create a DOM document and load the HTML data
$xmlDoc = new DomDocument;
// this dumps out the warnings
$xmlDoc->loadHTML($fetchResult);
Run Code Online (Sandbox Code Playgroud)
这个:
@$xmlDoc->loadHTML($fetchResult)
Run Code Online (Sandbox Code Playgroud)
可以抑制警告,但我如何以编程方式捕获这些警告?
tho*_*ter 210
呼叫
libxml_use_internal_errors(true);
Run Code Online (Sandbox Code Playgroud)
用...处理之前 $xmlDoc->loadHTML()
这告诉libxml2 不要向PHP 发送错误和警告.然后,要检查错误并自己处理它们,您可以在准备好时查阅libxml_get_last_error()和/或libxml_get_errors().
Ja͢*_*͢ck 88
要隐藏警告,您必须提供libxml
内部使用的特殊指令来执行解析:
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
Run Code Online (Sandbox Code Playgroud)
在libxml_use_internal_errors(true)
表明你要处理的错误和警告自己,你不希望他们弄乱你的脚本的输出.
这与@
运营商不同.警告会在幕后收集,之后您可以通过使用来检索它们libxml_get_errors()
,以防您希望执行记录或将问题列表返回给调用者.
无论您是否使用收集的警告,都应始终通过调用清除队列libxml_clear_errors()
.
保持国家
如果您有其他使用libxml
它的代码,可能值得确保您的代码不会改变错误处理的全局状态; 为此,您可以使用返回值libxml_use_internal_errors()
来保存以前的状态.
// modify state
$libxml_previous_state = libxml_use_internal_errors(true);
// parse
$dom->loadHTML($html);
// handle errors
libxml_clear_errors();
// restore
libxml_use_internal_errors($libxml_previous_state);
Run Code Online (Sandbox Code Playgroud)
tro*_*skn 14
您可以使用安装临时错误处理程序 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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
// 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());
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*Ott 12
设置选项"LIBXML_NOWARNING"和"LIBXML_NOERROR"也可以很好地工作:
$dom->loadHTML($html, LIBXML_NOWARNING | LIBXML_NOERROR);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41219 次 |
最近记录: |