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.
It’s because the page Character Not Found page returns a
404 Not FoundHTTP response code, which makes a lot of sense, but is considered an error.File functions, such as
file_get_contents, will returnfalseby 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_decodecan parse it, you need to use a context: