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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3431169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:44:11  来源:igfitidea点击:

Good error handling with file_get_contents

phperror-handling

提问by Abs

I am making use of simplehtmldomwhich has this funciton:

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

I use it like so:

我像这样使用它:

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

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:

有时,一个 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

Line 39 is in the above code.

第 39 行在上面的代码中。

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

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

Thanks all for any help

感谢大家的帮助

Update

更新

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;

}

采纳答案by quantumSoup

Here's an idea:

这是一个想法:

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;
    }
}

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

基本上是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); 

Now you can:

现在你可以:

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

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

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

回答by Treffynnon

Use CURLto get the URL and handle the error response that way.

使用CURL获取 URL 并以这种方式处理错误响应。

Simple example from curl_init():

curl_init() 的简单示例:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

回答by madmuffin

From my POV, good error handling is one of the big challenges in PHP. Fortunately you can register your own Error Handler and decide for yourself what to do.

从我的观点来看,良好的错误处理是 PHP 中的一大挑战。幸运的是,您可以注册自己的错误处理程序并自行决定要做什么。

You can define a fairly simple error handler like this:

您可以像这样定义一个相当简单的错误处理程序:

function throwExceptionOnError(int $errorCode , string $errorMessage) {
    // Usually you would check if the error code is serious
    // enough (like E_WARNING or E_ERROR) to throw an exception
    throw new Exception($errorMessage);
}

and register it in your function like so:

并将其注册到您的函数中,如下所示:

function file_get_html() {
    $dom = new simple_html_dom;
    $args = func_get_args();
    set_error_handler("throwExceptionOnError");
    $dom->load(call_user_func_array('file_get_contents', $args), true);
    restore_error_handler();
    return $dom;
}

回答by prodigitalson

IF youre fetching from an external URL the best handling is going to come fromt he introduction of HTTP library like Zend_Http. This isnt much different than using CURL or fopen except its going to extract the particulars of these "dirvers" into a universal API and then you can choose which you want to use. Its also going to have some built in error trapping to make it easier on you.

如果您从外部 URL 获取,最好的处理将来自引入 HTTP 库(如 Zend_Http)。这与使用 CURL 或 fopen 没有太大区别,除了它将这些“驱动程序”的详细信息提取到通用 API 中,然后您可以选择要使用的。它还会有一些内置的错误捕获功能,让您更轻松。

If you dont want the overhead of another library then you can code it yourself obviously - in which case i always prefer CURL.

如果您不想要另一个库的开销,那么您显然可以自己编写代码 - 在这种情况下,我总是更喜欢 CURL。