通过JSON访问错误代码

时间:2017-10-26 03:57:05

标签: php json error-handling

所以我有一个邮政编码搜索,用户输入的邮政编码是11111,但是API丢了一个错误代码。我似乎无法访问错误代码,因为只要从file_get_contents获取它,它就会在我对file_get_contents执行var_dump后返回bool(false)。

这是我的API调用/密钥,我将在此帖后免费更改。

https://www.zipcodeapi.com/rest/rKbIzyDeg9hE9aDgCCV3tRUldiTsl5WMQ7upG8EWhVAq5eHIQCLjuGFHYyajE66u/info.json/11111/mile

这是我的代码。

$zipcodes = file_get_contents('https://www.zipcodeapi.com/rest/rKbIzyDeg9hE9aDgCCV3tRUldiTsl5WMQ7upG8EWhVAq5eHIQCLjuGFHYyajE66u/info.json/11111/mile')

//Keep getting bool(false) here after var_dump($zipcodes)

$zipcodes =json_decode($zipcodes);

如何访问错误代码?在解码之后我尝试了$ zipcodes-> error_code但没有。

1 个答案:

答案 0 :(得分:1)

您应该检查the $http_response_header variable

  

... $ http_response_header将填充HTTP响应标头

示例:

<?php

$zipcodes = file_get_contents('https://www.zipcodeapi.com/rest/rKbIzyDeg9hE9aDgCCV3tRUldiTsl5WMQ7upG8EWhVAq5eHIQCLjuGFHYyajE66u/info.json/11111/mile');

var_dump($zipcodes);

// Output:
bool(false)

// -------

var_dump($http_response_header);

// Output:
array(7) {
  [0] =>
  string(22) "HTTP/1.1 404 Not Found"
  [1] =>
  string(35) "Date: Thu, 26 Oct 2017 04:03:51 GMT"
  [2] =>
  string(60) "Server: Apache/2.4.27 (Amazon) OpenSSL/1.0.2k-fips PHP/7.1.7"
  [3] =>
  string(23) "X-Powered-By: PHP/7.1.7"
  [4] =>
  string(18) "Content-Length: 62"
  [5] =>
  string(17) "Connection: close"
  [6] =>
  string(30) "Content-Type: application/json"
}

// -------

$httpCode = explode(' ', $http_response_header[0])[1];
var_dump($httpCode);

// Output:
string(3) "404"