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

Abs*_*Abs 18 php error-handling

我正在使用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)

qua*_*oup 15

这是一个想法:

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

基本上是一个包装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); 
Run Code Online (Sandbox Code Playgroud)

现在你可以:

try {
    $html3 = file_get_html(trim("$link")); 
} catch (Exception $e) {
    // handle error here
}
Run Code Online (Sandbox Code Playgroud)

错误抑制(通过使用@或通过降低error_reporting级别是一个有效的解决方案.这可以抛出异常,您可以使用它来处理您的错误.有很多原因file_get_contents可能会产生警告,PHP的手册本身建议降低error_reporting:请参阅手册

  • 这不是很好的错误处理.这是错误抑制. (3认同)