开发者

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

开发者 https://www.devze.com 2023-03-12 07:59 出处:网络
Here is a JSON data example saved in a file data.txt [ 开发者_开发知识库{\"name\":\"yekky\"}, {\"name\":\"mussie\"},

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?


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));


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.


$file = 'data.txt';
$data = json_decode(file_get_contents($file));
foreach ($data as $key => $obj) {
    $obj->num = (string)($key+1);
}
file_put_contents($file, json_encode($data));
0

精彩评论

暂无评论...
验证码 换一张
取 消