PHP json_decode() returns NULL with seemingly valid JSON?

There are a few possible reasons that json_decode() might return NULL when given what appears to be valid JSON. Here are a few things you might want to check:

  1. Make sure that the input string is actually a valid JSON string. You can use an online JSON linting tool to validate the syntax of your JSON string.

  2. Make sure that you are using the correct encoding when you read the JSON string from a file or receive it as a response from a network request. json_decode() expects UTF-8 encoded input, so if you are reading from a file that is encoded differently, or if you are receiving the JSON string from a network request that has a different encoding, json_decode() may not be able to parse it properly.

  3. Make sure that you are using the correct second argument for json_decode(). If you pass TRUE as the second argument, json_decode() will return an associative array instead of an object. If you pass FALSE, it will return an object. If you pass something other than these two values (e.g. NULL), json_decode() will return the value of the second argument if it is unable to decode the JSON string.

  4. Make sure that there are no whitespace characters (e.g. newlines, tabs) before or after the JSON string. These characters can cause json_decode() to fail, even if the JSON string itself is valid.

Watch a course Learn object oriented PHP

I hope this helps! Let me know if you have any other questions.