相关疑难解决方法(0)

使用file_get_contents进行良好的错误处理

我正在使用simplehtmldom,它有这个功能:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

$html3 = file_get_html(urlencode(trim("$link")));
Run Code Online (Sandbox Code Playgroud)

有时,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
Run Code Online (Sandbox Code Playgroud)

第39行在上面的代码中.

我怎样才能正确处理这个错误,我可以只使用普通if条件,它看起来不像是返回一个布尔值.

谢谢大家的帮助

更新

这是一个好的解决方案吗?

if(fopen(urlencode(trim("$next_url")), 'r')){

    $html3 = file_get_html(urlencode(trim("$next_url")));

}else{
    //do other stuff, error_logging
    return false;

}
Run Code Online (Sandbox Code Playgroud)

php error-handling

18
推荐指数
1
解决办法
3万
查看次数

标签 统计

error-handling ×1

php ×1