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.
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:
json_decode(file_get_contents($url), true) to: json_decode(file_get_contents($url), false) and tried accessing $var as an object.file_get_contents($url)I posted on the battle.net API forums but i thought i would try here as well.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With