如何停止错误消息,如果JSON文件无法打开流
这是错误,我得到了
警告:file_get_contents( https://api.themoviedb.org/3 /movie/39740?api_key = 522cec78237f49axxxxxxxxxxx6d1e0c834a ):打开流失败:HTTP请求失败!找不到HTTP/1.1 404
Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
现在,您可能是创始人,该链接的内容是什么?
Now, you may founder, what is inside that link?
该页面仅包含此行
{状态代码":34,状态消息":找不到您请求的资源."}
{"status_code":34,"status_message":"The resource you requested could not be found."}
所以,我认为这是一个有效的页面(可以在浏览器中打开该页面).如果打开流失败,我只是希望PHP停止给出此错误.
So, I think this is a valid page (which i can open in browser). I just want PHP to stop giving this error, if it failed to open stream.
这是我的JSON代码
$response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
$response = json_decode($response, true);
}
它不是该问题的重复项.这个问题与电子邮件和密码有关,而我的则不是
It is not duplicate of that question. That question is related to email and password, where mine is not
尝试使用curl获取http响应代码并在404时执行操作
Try to use curl to get the http response code and act when it's 404
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$responsejson = curl_exec($ch);
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
// do your normal process
$response = json_decode($responsejson, true);
break;
case 404:
// do your thing for not found situation
$response = 'Not found';
break;
case 401:
// not allowed
$response = 'api key wrong?';
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}
// close cURL resource, and free up system resources
curl_close($ch);
?>