【问题标题】:How to stop the error message, If JSON file failed to open stream如何停止错误消息,如果 JSON 文件无法打开流
【发布时间】:2017-07-08 12:12:39
【问题描述】:

这是错误,我得到了

警告:file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a):打开流失败:HTTP 请求失败! HTTP/1.1 404 未找到

现在,你可能是创始人,那个链接里面是什么?

那个页面只包含这一行

{"status_code":34,"status_message":"找不到您请求的资源。"}

所以,我认为这是一个有效的页面(我可以在浏览器中打开)。如果 PHP 无法打开流,我只希望 PHP 停止给出此错误。

这是我的 JSON 代码

 $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
    $response = json_decode($response, true);
}

编辑:它不是那个问题的重复。这个问题与电子邮件和密码有关,我的不是

【问题讨论】:

标签: php json


【解决方案1】:

尝试 coreect 或不正确的选项 如果(响应===“正确”){ }

【讨论】:

  • 首先检查这个条件 if($content === FALSE) { }。如果您仍然遇到同样的问题,请在调用 file_get_contents() 之前使用 @: $content = @file_get_contents($site);
【解决方案2】:

尝试使用curl获取http响应码,在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);
?>

【讨论】:

    猜你喜欢
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2012-07-22
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多