Joanmi
Joanmi

Reputation: 442

How insert content of TXT file to JSON file

I want import the "links" from a links.txt file and put it on a JSON file but the result is like:

{"domain":[ "www.google.es","www.yahoo.com","www.example.com"],
 "id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
 "id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
 "id":6
}

Expected:

{"domain":"www.google.es","id":6},
{"domain":"www.yahoo.com"],"id":7},
{"domain":["www.example.com"],"id":8}

As you can see, the id is the same at I want differents id and the links are added 3 times the 3 links and I want add 1 link on 1 option.

<?php
$jsonContents = file_get_contents('data/data.json');
$data = json_decode($jsonContents, true);
$fp = 'links.txt';
$last_item = end($data);
$last_item_id = $last_item['id'];
$contents_arr = file($fp,FILE_IGNORE_NEW_LINES);
foreach($contents_arr as $key=>$value) {
    $contents_arr[$key] = rtrim($value, "\r");
    $data[] = array(
        'domain' => $contents_arr,
        'id' => $last_item_id+1,

    );
}
$json = json_encode($data);
file_put_contents('data/data.json', $json);

Upvotes: 1

Views: 956

Answers (1)

Petr
Petr

Reputation: 1179

$last_item_id+1 returns $last_item_id+1, it does not change $last_item_id variable.

Dont change $contents_arr array used for loop inside the loop.

You use for domain $contents_arr, which contains all values. Create for domain new array, ie:

foreach($contents_arr as $key=>$value) {
    $data[] = array(
        'domain' => [rtrim($value, "\r")],
        'id' => ++$last_item_id,
    );
}

Upvotes: 3

Related Questions