Carlitos
Carlitos

Reputation: 419

Accessing the Error code through JSON

So I have a zip code search and a user has typed in a zip code of 11111 but the API threw back an error code. I can't seem to access the error code because as soon as get it from file_get_contents it returns bool(false) after I do a var_dump on file_get_contents.

Here is my API call/key which I will change since its free after this post.

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

Here is my code.

$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);

How do I access the error code? I tried doing $zipcodes->error_code after decoding it but nothing.

Upvotes: 0

Views: 65

Answers (1)

terales
terales

Reputation: 3200

You should check the $http_response_header variable:

…$http_response_header will be populated with the HTTP response headers

Example:

<?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"

Upvotes: 1

Related Questions