Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object is NULL when data from URL is small?

Tags:

json

php

I have a JSON object im decoding from a url like so:

    $var = json_decode(file_get_contents($url), true);

The data i am getting is from the new battle.net API that is returned as a JSON object containing character data.

  • Here is an actual link where the character is found and there is data to be generated: Character Found.
  • Now here is a link for a character that does not exist and generates and error: Character Not Found.

Errors are returned as JSON objects that contain "status" and "reason" attributes. The value of the "status" attribute will always be "nok".

My problem is when the character is NOT FOUND the JSON object $var is NULL where if it is FOUND the JSON object $var contains the correct data. I need to be able to check whether the status is "nok" so i can output the apropriate error message

I have:

  • Checked the links to make sure they are generating correctly.
  • Changed json_decode(file_get_contents($url), true) to: json_decode(file_get_contents($url), false) and tried accessing $var as an object.
  • Tried using cURL instead of file_get_contents($url)

I posted on the battle.net API forums but i thought i would try here as well.

like image 258
JaredTS486 Avatar asked Jun 17 '26 01:06

JaredTS486


1 Answers

It's because the page Character Not Found page returns a 404 Not Found HTTP response code, which makes a lot of sense, but is considered an error.

File functions, such as file_get_contents, will return false by default when encountering an error (404, 500, etc.) on a HTTP stream wrapper.

In order to ignore the error and return the content anyway, so that json_decode can parse it, you need to use a context:

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$var = json_decode(file_get_contents($url, false, $context), true);
like image 68
netcoder Avatar answered Jun 19 '26 15:06

netcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!