简体   繁体   中英

PHP/MySQL/JSON - Looping through all pages of JSON response

I am calling the Crunchbase API and it gives me long response, so long that the response has multiple pages that can be accessed with ?page=# at the end of the api url.

My question is how do I write some code to run the script once and it will go through all of the pages available without me having the change the page number every time I call the script?

Simplified version of my code:

$url = "https://api.url.com/tags/?page=2";
$jsondata = file_get_contents($url);
$array = json_decode($jsondata,true);

var_dump($array);

foreach($array as $key => $value) {

mysql_query(" INSERT into cbcompanies (
  `column1`)

VALUES (
  '{$value['foo']}') ",$con);

}

If you want to make multiple requests you have to use loops or explicitly get all the pages.

$numberOfPages = 100;
for($i = 1; $i < $numberOfPages; $i++) {
    $url = sprintf("https://api.url.com/tags/?page=%d", $i);

    // Rest of the code.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM