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

2021-12-26 00:00:00 error-handling php

我正在使用具有此功能的 simplehtmldom:

I am making use of simplehtmldom which has this funciton:

// 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 警告:

Sometimes, a URL may just not be valid and I want to handle this. I thought I could use a try and catch but this hasn't worked since it doesn't throw an exception, it just gives a php warning like this:

[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 行在上面的代码中.

Line 39 is in the above code.

我如何正确处理这个错误,我可以只使用一个简单的 if 条件,它看起来不像返回一个布尔值.

How can i correctly handle this error, can I just use a plain ifcondition, it doesn't look like it returns a boolean.

感谢大家的帮助

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

Is this a good solution?

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 本身,您可以

Basically a wrapper to file_get_contents. It will throw an exception on failure. To avoid having to override file_get_contents itself, you can

// 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 级别是一个有效解决方案.这可能会引发异常,您可以使用它来处理您的错误.有file_get_contents 可能产生警告的原因有很多,PHP 的手册本身建议降低 error_reporting:参见手册

Error suppression (either by using @ or by lowering the error_reporting level is a valid solution. This can throw exceptions and you can use that to handle your errors. There are many reasons why file_get_contents might generate warnings, and PHP's manual itself recommends lowering error_reporting: See manual

相关文章