You are passing to json_decode
a string that is not valid JSON, this is the reason NULL
is returned.
As I see from comments inspecting the error code generated gives 4
that corresponds to the constant JSON_ERROR_SYNTAX
that just means the JSON string has a Syntax Error.
(See http://php.net/manual/en/function.json-last-error.php)
You should inspect (echo) what you get from
$str = file_get_contents('http://localhost/data.json');
(You may edit your answer and post it - or a portion of it)
For sure it is not valid JSON
; the problem lies there: in data.json
.
Then as you fix things and get from data.json
what is expected I would ensure you really need to use html_entity_decode
on the fetched data.
It would be "weird" to have html encoded JSON data.
UPDATE
Looking at what you get from data.json
it seem the JSON data contains actually HTML entities (as I see the presence of
s)
This is actually weird, the right thing to do would be to fix how data.json
is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json
.
We can't deepen this here as I don't know where does data.json
come from or the code that generates it. Eventually you may post another answer.
So here is a quick fix provided that the right approach would be what I just suggested above.
As you decode html entities, non breaking spaces
turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data.
The idea is to remove these characters; your code becomes:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
// the character sequence for decoded HTML
$nbsp = html_entity_decode( " " );
// remove every occurrence of the character sequence
$decodedstr = str_replace( $nbsp, "", $decodedstr );
$jarray = json_decode($decodedstr, true);