Ali
Ali

Reputation: 91

How to save each row of json file

in this functions, I'm about to save the users.json in logs directory. then save each row of the saved file in separated files: user_1.json, user_2.json, user_3.json.

The Problem: the saved file, such as user_1.json is empty. and i don't know what`s wrong

here is what I've done:

<?php
file_put_contents('logs/users.json',file_get_contents('http://webtrim.ir/json/users.json'));
$user_list = file_get_contents('logs/users.json');
$user_list = json_decode($user_list, false);
$all_users = $user_list->data[0]->users->data;

// Saving Method 

foreach ($all_users as $key => $user) {
    $user_id = $user->id;
    file_put_contents('logs/user_' . $user_id . '.json', $user);
}

Upvotes: 0

Views: 229

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94662

I think all you need to do is decode the array back into JSON before you put it into the new file

<?php
file_put_contents('logs/users.json',file_get_contents('http://webtrim.ir/json/users.json'));
$user_list = file_get_contents('logs/users.json');
$user_list = json_decode($user_list, false);
$all_users = $user_list->data[0]->users->data;

// Saving Method 

foreach ($all_users as $key => $user) {
    file_put_contents('logs/user_' . $user->id . '.json', json_encode($user));
    //             changed code      ^^^^            ^^^^^^^^^^^
}

Amended to use the users id and not the occurance of the array ( Sorry, my fault).

That will get you into another problem as the id of 3 is used for Sara and Jack, but it would appear to be unique if you were to use id and cat but you will have to check that with the file producer or a larger dataset

So you could try

<?php
file_put_contents('logs/users.json',file_get_contents('http://webtrim.ir/json/users.json'));
$user_list = file_get_contents('logs/users.json');
$user_list = json_decode($user_list, false);
$all_users = $user_list->data[0]->users->data;

// Saving Method 

foreach ($all_users as $user) {
    $uniq = $user->id . $user->cat;
    file_put_contents("logs/user_$uniq.json", json_encode($user));
}

Upvotes: 1

Scaramouche
Scaramouche

Reputation: 3267

Firstly, you should use $key instead of $user->id because user IDs are not unique and you are rewriting some files and losing info, for instance, Jack and Sara have both id=3, so you're rewriting Jack's info with Sara's.

The actual problem of why your json files are empty is because you forgot to json_encode the info before saving it to disk again.

Change:

file_put_contents('logs/user_' . $user_id . '.json', $user);

with:

file_put_contents('logs/user_' . $key . '.json', json_encode($user));

Upvotes: 3

Related Questions