我正在利用简单的htmldom http://simplehtmldom.sourceforge.net/它有这个功能:
// get html dom form file
function file_get_html() {
$dom = new simple_html_dom;
$args = func_get_args();
$dom->load(call_user_func_array('file_get_contents', $args), true);
return $dom;
}
我这样使用它:
$html3 = file_get_html(urlencode(trim("$link")));
有时,URL 可能无效,我想处理这个问题。我以为我可以使用 try 和 catch,但这并没有起作用,因为它不会抛出异常,它只是给出一个像这样的 php 警告:
[06-Aug-2010 19:59:42] PHP Warning: file_get_contents(http://new.mysite.com/ghs 1/) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/example/public_html/other/simple_html_dom.php on line 39
上面代码中的第39行。
我怎样才能正确处理这个错误,我可以只使用一个简单的if
条件,它看起来不像返回布尔值。
感谢大家的帮助
Update
这是一个好的解决方案吗?
if(fopen(urlencode(trim("$next_url")), 'r')){
$html3 = file_get_html(urlencode(trim("$next_url")));
}else{
//do other stuff, error_logging
return false;
}
这是一个想法:
function fget_contents() {
$args = func_get_args();
// the @ can be removed if you lower error_reporting level
$contents = @call_user_func_array('file_get_contents', $args);
if ($contents === false) {
throw new Exception('Failed to open ' . $file);
} else {
return $contents;
}
}
基本上是一个包装器file_get_contents
。失败时它将引发异常。
为了避免必须覆盖file_get_contents
本身,你可以
// change this
$dom->load(call_user_func_array('file_get_contents', $args), true);
// to
$dom->load(call_user_func_array('fget_contents', $args), true);
现在你可以:
try {
$html3 = file_get_html(trim("$link"));
} catch (Exception $e) {
// handle error here
}
错误抑制(通过使用@
或者通过降低 error_reporting 级别是valid解决方案。这可能会引发异常,您可以使用它来处理错误。原因有很多file_get_contents
可能会生成警告,PHP 手册本身建议降低 error_reporting:参见手册 http://php.net/manual/en/function.file-get-contents.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)