我有2個不同的php文件用於從API中提取數據和用於存儲數據的一個JSON文件。我想,當我在服務器上運行的每個PHP文件,我的JSON文件將存儲陣列從兩個PHP文件。 E.g:如何將數組存儲到來自2個不同的php文件的json文件中
store.json
{
"articles": [{
"author": "Rozina Sabur",
"title": "John Cleese to return to new BBC sitcom Edith - despite saying he would never be back",
"description": "Almost 40 years on from his starring role in Fawlty Towers, John Cleese is set to return to the BBC for a new sitcom.",
"url": "http:\/\/www.telegraph.co.uk\/news\/2017\/04\/11\/john-cleese-return-new-bbc-sitcom-edith-despite-saying-would\/",
"publishedAt": "2017-04-11T22:10:11Z"
}]
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
"nationality": "Spain",
"contractUntil": "2021-06-30",
"marketValue": "9,000,000 €"
}]
}
first.php
$url = ('myAPI.com');
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$values = array();
$resp = array();
$date = date('Y-m-d H:m:s');
//get the employee details
foreach ($data['players'] as $myp) {
$name = $myp['name'];
$posi = $myp['position'];
$nation = $myp['nationality'];
$market = $myp['marketValue'];
$values[] = array('name' => $name, 'position' => $posi, 'nationality' => $nation, 'marketValue' => $market, 'created' => $date);
}
$resp['players'] = $values; //HERE IS THE PART (PLATERS)
$fp = fopen('myJson.json', 'w');
fwrite($fp, json_encode($resp));
fclose($fp);
second.php的代碼非常相像first.php只是API差異的。
.......
........
$values[] = array('author' => $author, 'title' => $title, 'description' => $descrip, 'url' => $ur, 'publishedAt' => $publish);
}
$resp['articles'] = $values; //HERE IS THE MAIN POINT (ARTICLES)
$fp = fopen('myJson.json', 'w');
fwrite($fp, json_encode($resp));
fclose($fp);
我的問題是,當我運行first.php數組替換second.php,反之亦然。我如何修復它,以便從JSON文件都PHP文件存儲如上面的store.php文件陣列。
上比2個DIFF PHP文件的其他最佳做法的其他想法是值得歡迎的。
感謝