如何将数组存储到来自2个不同php文件的json文件中

时间:2017-04-11 22:41:49

标签: php arrays json

我有2个不同的php文件用于从API获取数据,还有一个JSON文件用于存储数据。我希望当我在服务器上运行每个PHP文件时,我的Json文件将存储来自两个PHP文件的数组。 E.g:

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 diff。

.......
........
$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的数组,反之亦然。如何修复它,以便来自两个PHP文件的数组存储在JSON文件中,就像上面的store.php文件一样。

欢迎关于除2 diff php文件之外的最佳实践的其他想法。

由于

3 个答案:

答案 0 :(得分:0)

因为这两个程序都打开了文件' w'

将其更改为此

 $fp = fopen('myJson.json','a');

就像一个注释,这不是一个有效的单个json文件',而是一个有效json行的文件。

答案 1 :(得分:0)

    $fp = fopen('myJson.json', 'a');
fwrite($fp, json_encode($resp));
fclose($fp);

使用a标志来保留最后的数据

答案 2 :(得分:0)

将此方法添加到PHP文件中,并在两个PHP文件中需要此文件。

function storeJson($data, $type)
{
    $prevData = file_get_contents('store.json');
    $arrayData = json_decode($prevData, true);
    if(in_array($type, array_keys($arrayData))) {
        $arrayData[$type] = $data;
        $fp = fopen('store.json', 'w');
        fwrite($fp, json_encode($arrayData));
        fclose($fp);
    }
}

在first.php文件末尾调用方法

storeJson($resp, 'players');

在second.php文件中

storeJson($resp, 'articles');