首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用file_get_contents进行良好的错误处理

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

Stack Overflow用户
提问于 2010-08-08 00:29:56
回答 3查看 27.7K关注 0票数 19

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

代码语言:javascript
复制
// 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;
}

我这样使用它:

代码语言:javascript
复制
$html3 = file_get_html(urlencode(trim("$link")));

有时,URL可能就是无效的,我想处理这个问题。我想我可以使用try and catch,但这并没有起作用,因为它没有抛出异常,它只是给出了一个php警告,如下所示:

代码语言:javascript
复制
[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行在上面的代码中。

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

感谢所有人的帮助

更新

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

代码语言:javascript
复制
if(fopen(urlencode(trim("$next_url")), 'r')){

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

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

}
EN

回答 3

Stack Overflow用户

发布于 2010-08-08 00:39:41

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

来自curl_init()的简单示例

代码语言:javascript
复制
<?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);
?>
票数 4
EN

Stack Overflow用户

发布于 2020-08-21 03:25:03

要了解file_get_contents调用可能失败的原因,只需使用php的error_get_last函数:

代码语言:javascript
复制
if ($contents = file_get_contents($url)) {
    // it worked
}
else {
   die("Failed to fetch ".$url.", error: ".error_get_last()['message']);
}
票数 1
EN

Stack Overflow用户

发布于 2010-08-08 00:46:38

如果你是从外部的URL获取,最好的处理方法是引入Zend_Http这样的超文本传输协议库。这与使用CURL或fopen没有太大不同,只是它会将这些“驱动程序”的细节提取到一个通用的API中,然后您可以选择要使用的驱动程序。它还会有一些内置的错误陷阱,让你更容易。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3431169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档