使用file_get_contents处理好的错误 [英] Good error handling with file_get_contents

查看:137
本文介绍了使用file_get_contents处理好的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有此功能的 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")));

有时,网址可能无效,我想处理这个。我以为我可以使用一个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.

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

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

这篇关于使用file_get_contents处理好的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆