Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to update JSON data in a txt file?

Tags:

json

php

Here is a JSON data example saved in a file data.txt

   [
     {"name":"yekky"},
     {"name":"mussie"},
     {"name":"jessecasicas"}
     ...// many rows
    ]

I would like to update the file so it will look like this:

[
 {"name":"yekky","num":"1"},
 {"name":"mussie","num":"2"},
 {"name":"jessecasicas","num":"3"}
 ...// many rows
]

This is what I have got so far:

$json_data = file_get_contents('data.txt');
// What goes here?

And how do I count how many rows there are in the JSON tree?

like image 578
fish man Avatar asked Dec 27 '22 19:12

fish man


2 Answers

Use json_decode() to decode the JSON data in a PHP array, manipulate the PHP array, then re-encode the data with json_encode().

For example:

$json_data = json_decode(file_get_contents('data.txt'), true);
for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
    $json_data[$i]['num'] = (string) ($i + 1);
}
file_put_contents('data.txt', json_encode($json_data));
like image 123
rid Avatar answered Jan 04 '23 17:01

rid


You should use the PHP JSON library for such tasks. For example, after having read your JSON data from the file, do something like:

$json = json_decode($json_data);
$itemCount = count($json);

After having modified your JSON data, just encode it again:

$json_data = json_encode($json);

Also, you seem to want to beatify your JSON data. My advise is to just use whatever comes out of json_encode and save that to your file, because it will probably be the smallest (in file size) possible representation of your JSON data.

If you format it in a way readable for humans, you've got lots of extra spaces / tabs / line-breaks which increase file size and parsing time.

If you need to read it yourself, you can still beautify your JSON data by hand.

like image 41
fresskoma Avatar answered Jan 04 '23 18:01

fresskoma