如何停止错误消息,如果JSON文件无法打开流 [英] How to stop the error message, If JSON file failed to open stream

查看:80
本文介绍了如何停止错误消息,如果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);
?>

这篇关于如何停止错误消息,如果JSON文件无法打开流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆