如果我像这样打开一个外部文件:
$source = @file_get_contents('http://somewebsite.com/todaysinfo/');
$decode = json_decode($source, true);如何检查http调用是否成功(翻页或其他)?
if ($source) { // will this re-load the page and check for TRUE return?
// success
}或者我可以/应该这样做(一次设置并检查源代码)
if ($source = @file_get_contents('http://somewebsite.com/todaysinfo/')) {
// success
$decode = json_decode($source, true);
}发布于 2014-08-11 03:16:28
要检查服务器是否没有返回HTTP200,您应该使用cURL,因为file_get_contents()并不关心HTTP-Code,只要远程主机没有关闭,它就会返回任何内容。
$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()并检查返回的字符串是否为空。
$source = file_get_contents('http://somewebsite.com/todaysinfo/');
if($source !== false AND !empty($source)) {
$decode = json_decode($source, true);
}发布于 2014-08-11 03:05:47
if ($source) { // will checking like this add a re-load?不,不会的。由于file_get_contents在失败时返回false,因此这是一种很好的测试方法,除了仅包含空格、0或空白的页面也将被视为失败。这可能不是您想要的。
在这种情况下,您需要执行以下操作:
if ($source !== false) {https://stackoverflow.com/questions/25231980
复制相似问题