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, "");
$data[] = array(
'domain' => $contents_arr,
'id' => $last_item_id+1,
);
}
$json = json_encode($data);
file_put_contents('data/data.json', $json);