YMI
YMI

Reputation: 165

PHP json_decode returns null

I'm writing PHP code that uses a database. To do so, I use an array as a hash-map. Every time content is added or removed from my DB, I save it to file.

I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).

I built two functions:

function saveDB($db){
    $json_db = json_encode($db);
    file_put_contents("wordsDB.json", $json_db);
} // saveDB

function loadDB(){
    $json_db = file_get_contents("wordsDB.json");
    return json_decode($json_db, true);
} // loadDB

When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).

The json string itself is very long (~200,000 characters, and that's just for testing).

I tried the following:

json_last_error() doesn't work. I get no error number (Get null, not 0).

It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.

I believe the size has something to do with it, because small strings seem to work fine.

Thanks Everybody :)

Upvotes: 2

Views: 4397

Answers (4)

Cliffordlife
Cliffordlife

Reputation: 470

Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.

Kickself #124

Upvotes: 0

Odinn
Odinn

Reputation: 808

In your JSON file change null to "null" and it will solve the problem.

Upvotes: 3

Boris Belenski
Boris Belenski

Reputation: 1412

Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.

EDIT: After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:

"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":

Change that null to be valid property name and json_decode will do the job.

Upvotes: 3

Rayfloyd
Rayfloyd

Reputation: 273

I had a similar problem last week. my json was valid according to jsonlint.com.

My json string contained a # and a & and those two made json_decode fail and return null.

by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.

I suggest var_dumping and using find dunction to look for these king of characters.

Upvotes: 0

Related Questions