Cyberio Cyberio - 2 days ago 4
JSON Question

Writing and reading an array with specified keys to a json file

I have an array

$monthlyStatistics = array('total' => 1, 'opened' => 1, 'clicked' => 1, 'bounced' => 1, 'optout' => 1);


that I have saved to a json file

$monthlypath = '/storage/monthlytotals.json';
file_put_contents($monthlypath, json_encode($monthlyStatistics));


and I need to read this json file and output the contents as an array with the specified keys. I am currently doing this:

$monthlypath = '/storage/monthlytotals.json';
$read_file = file_get_contents($monthlypath);
$monthlytotals = json_decode($read_file);


which I know that file_put_contents puts as a string and that file() is supposed to read the entire file into an array (which I am currently not using since it doesn't read what file_put_contents wrote).

Am I doing this wrong or am I missing a function that is supposed to go along with file() for writing it properly as an array?

Answer

You're trying to convert from a PHP data structure in memory to something that can be written to disk. Somehow that needs serialising - either through json_encode() or serialize() etc.

file() reads a file into a list of lines (one line per array entry).

For what you're doing,

file_put_contents($monthlypath, json_encode($totals))

and

$totals = json_decode(file_get_contents($monthlypath), true)

are probably all you probably need.