首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查file_get_contents

检查file_get_contents
EN

Stack Overflow用户
提问于 2014-08-11 02:59:57
回答 2查看 9.4K关注 0票数 1

如果我像这样打开一个外部文件:

代码语言:javascript
复制
$source = @file_get_contents('http://somewebsite.com/todaysinfo/');
$decode = json_decode($source, true);

如何检查http调用是否成功(翻页或其他)?

代码语言:javascript
复制
if ($source) { // will this re-load the page and check for TRUE return?

   // success

}

或者我可以/应该这样做(一次设置并检查源代码)

代码语言:javascript
复制
if ($source = @file_get_contents('http://somewebsite.com/todaysinfo/')) {

   // success
   $decode = json_decode($source, true);

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-11 03:16:28

要检查服务器是否没有返回HTTP200,您应该使用cURL,因为file_get_contents()并不关心HTTP-Code,只要远程主机没有关闭,它就会返回任何内容。

代码语言:javascript
复制
$ch = curl_init('http://somewebsite.com/todaysinfo/');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch) == 0 AND $http == 200) {
    $decode = json_decode($data, true);
}

编辑:只需使用file_get_contents()并检查返回的字符串是否为空。

代码语言:javascript
复制
$source = file_get_contents('http://somewebsite.com/todaysinfo/');
if($source !== false AND !empty($source)) {
    $decode = json_decode($source, true);
}
票数 3
EN

Stack Overflow用户

发布于 2014-08-11 03:05:47

代码语言:javascript
复制
if ($source) { // will checking like this add a re-load?

不,不会的。由于file_get_contents在失败时返回false,因此这是一种很好的测试方法,除了仅包含空格、0或空白的页面也将被视为失败。这可能不是您想要的。

在这种情况下,您需要执行以下操作:

代码语言:javascript
复制
if ($source !== false) {
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25231980

复制
相关文章

相似问题

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