Vikram Vikram - 6 months ago 17
PHP Question

json_decode returning an array of 1

I am trying to decode some JSON into a php array. Here's the code excerpt:

$getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}";
$arr = json_decode($getfile, true);
$arr['day3'] = $selecter;
echo(print_r($arr));


The only thing that gets returned is '1'. I've checked JSONLint and it is valid json, so I'm wondering why json_decode is failing. I also tried checking what the array is before adding the day3 key to it, and I still return a '1'. Any help is appreciated!

Actual code:

$getfile = "";
$getfile = file_get_contents($file);
if ($getfile == "") {
writeLog("Error reading file.");
}
writeLog("getfile is " . $getfile);
writeLog("Decoding JSON data");
$arr = json_decode($getfile, true);
writeLog("Decoded raw: " . print_r($arr));
writeLog("Editing raw data. Adding data for day " . $day);
$arr['day3'] = $selecter;
writeLog(print_r($arr));
$newfile = json_enconde($arr);
writeLog($newfile);
if (file_put_contents($file, $newfile)) {
writeLog("Wrote file to " . $file);
echo $newfile;
} else {
writeLog("Error writting file");
}


These are the contents of $file (it's a text file)

{"fname":"Bob","lname":"Thomas","cascade":"bthomas","loc":"res","place":"home 2"}

Answer

We still don't know what's in your file. However if:

"{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"

Then the extraneous outer double quotes will screw the JSON, and json_decode will return NULL. Use json_last_error() to find out. Might also be a UTF-8 BOM or something else ...

Anyway, the 1 is the result from print_r. print_r outputs directly, you don't need the echo. Also for debugging rather use var_dump()


More specifically you would want the print_r output returned (instead of the boolean success result 1) and then write that to the log.

So use:

      writeLog(print_r($arr, TRUE));

Notice the TRUE parameter.