Staffan Estberg Staffan Estberg - 21 days ago 10
JSON Question

PHP writes null to JSON file

I've seen similar posts to this question but I can't seem to figure it out. I have a small PHP script that reads and writes form input to a JSON file, like this –

$file = 'data.json';

$arr_data = array();

$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);

$jsondata = file_get_contents($file);

//var_dump($jsondata); returns whatever string content is in the file, so seems to work

$arr_data = json_decode($jsondata, true);

array_push($arr_data, $formdata);

//var_dump($arr_data); returns NULL, not sure what happens here

$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

file_put_contents($file, $jsondata);


Any ideas? Using PHP 5.5.9, checked that files are writeable. Both files have UTF8 encoding.

Answer Source

json_decode() will return NULL if the input is blank. Try this to ensure your $arr_data is an array...

$arr_data = json_decode($jsondata, true);
if ($arr_data === null) {
    $arr_data = [];
}