Steingrimur Jonsson Steingrimur Jonsson - 1 month ago 6
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.

{"Symbol":["A"],"PERatio":["31.55"],"MarketCap":["19722.500"],"Dividend":["0.87"],"ROE":["14.48"],"DebtToEbitda":["2.04"],"EbitdaGrowth":["5.40"],"RevenueGrowth":["4.20"]}{"Symbol":["AA"],"PERatio":["44.45"],"MarketCap":["6960.660"],"Dividend":["0.00"],"ROE":["2.33"],"DebtToEbitda":["0.95"],"EbitdaGrowth":["0.00"],"RevenueGrowth":["0.00"]}{"Symbol":["AAC"],"PERatio":["0.00"],"MarketCap":["217.730"],"Dividend":["0.00"],"ROE":["-2.76"],"DebtToEbitda":["8.71"],"EbitdaGrowth":["22.30"],"RevenueGrowth":["15.00"]}{"Symbol":["AAP"],"PERatio":["18.68"],"MarketCap":["6888.440"],"Dividend":["0.26"],"ROE":["12.69"],"DebtToEbitda":["1.17"],"EbitdaGrowth":["6.50"],"RevenueGrowth":["13.60"]}


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

$.getJSON('Stockdata1.json', function (data) {
console.log(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));