Steingrimur Jonsson Steingrimur Jonsson - 6 months ago 32
Javascript Question

file_put_content array structure does not work

I'm trying to move an array into a .json file and then simply console.log it. I think its my structure in my array that is messing it up.

$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
file_put_contents('Stockdata1.json', json_encode($jsonarray), FILE_APPEND);

This is how it looks like in the .json file.


when i then try to console.log in js like this

$.getJSON('Stockdata1.json', function (data) {

nothing comes out... Hope someone can see my mistake..

Answer Source

As soon as you FILE_APPEND the second array, you're invalidating the JSON in the file. The file will contain two JSON objects without a separator (i.e. (abbreviated for clarity) {"Symbol":["A"]}{"Symbol":["B"]}).

Instead, what you need for valid JSON, is to have the file contain a JSON array of all objects: [{"Symbol":["A"]},{"Symbol":["B"]}]. The only way to do that, is to not use file_put_contents() with the FILE_APPEND flag, but to load the file as JSON, add the new object, and write the full JSON back to the file.

My suggestion is to change your code to something along these lines:

$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth],  'RevenueGrowth' =>[$revenuegrowth],);

$data = json_decode(file_get_contents('Stockdata1.json'));

if (!$data) {
    // file is empty or does not contain valid JSON
    $data = [];
} elseif (is_object($data)) {
    // file only contains a JSON object, not a JSON array
    $data = [ $data ];

$data[] = $jsonarray;
file_put_contents('Stockdata1.json', json_encode($data));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download