Search code examples
phpjsonapifetch-apiarray-merge

How Can I Get Data From more then 1 page from JSON API and put them into 1 json file with PHP?


This Is My API URL :

https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=250&page=1

We Can Have page=2 AND page=3 AND etc ... I Want To Fetch Data From page 1 Until page 6 And Then Put All Of Them Into 1 json File file.json . I'm Using this code below :

    for ($j=1;$j<=6;$j++){
    $coin_market_cap_url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=250&page='.$j;
    $coin_market_cap_result = json_decode(getCurlAgent($coin_market_cap_url, true), true);
    for ($i=0;$i<250;$i++){
        $coins[$i]['name']=$coin_market_cap_result[$i]['name'];
        $coins[$i]['symbol']=$coin_market_cap_result[$i]['symbol'];
    }
}
$coins = json_encode($coins);
if ($coins){
    file_put_contents("file.json", $coins);
}

How Can I fix this?

Thanks


Solution

  • The problem is you are replacing the first 250 entries in the for loop

    Working Code

    <?php
    
    $coins = [];
    for ($j = 1; $j <= 6; $j++) {
        $coin_market_cap_url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=250&page={$j}";
        $coin_market_cap_result = json_decode(file_get_contents($coin_market_cap_url), true);
        foreach ($coin_market_cap_result as $coin) {
            $coins[] = [
                'name' => $coin['name'],
                'symbol' => $coin['symbol'],
            ];
        }
    }
    
    $coins = json_encode($coins);
    if ($coins) {
        file_put_contents("file.json", $coins);
    }