简体   繁体   中英

Execute php curl inside foreach looping

I'm trying to get an users data list throught an url with user ID parameter that return just one user data each time, but to get one user data, i need to change the user ID parameter inside url. In this case, i would like to use curl inside a foreach looping to get all data without need to change the user ID parameter each time.

In my php script, i tried to get all users data at once using while , but i know that this is not the correct way to do this and during my research here, i found some similiar questions that use foreach to execute curl, but unfortunatly i did not find a correct way to solve this:

  1. Using cURL in a foreach-loop (php)

  2. PHP Array cURL foreach

  3. curl execution inside foreach loop php

  4. JSON cURL - invalid argument for foreach() - PHP

Below is the php script that i'm trying to get all users data using while looping where i put curl inside:


// database connection file
include 'db_connection.php';

// prepared statement query
$stmt = $db -> prepare('SELECT userID FROM users'); 
$stmt -> execute(); 
$stmt -> store_result(); 
$stmt -> bind_result($userID);

//While looping

while($stmt -> fetch()){

// curl to get users data from api url
$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.user.com/api/user/'.$userID.'?key=8aaa03390f0842c6",
    
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

echo $response.'<br>';
    
}


As showed above, i put curl inside while looping but this is not a correct way to do this. In this case, how can i get all data throught url using curl inside php foreach?

I found a solution for my doubt. As @Barmar mentioned on his comment, i modified my script to get users information from api url using curl inside while loop as below:


//database connection
include 'db_connection.php';

$stmt = $db -> prepare('SELECT userID FROM users'); 
$stmt -> execute(); 
$stmt -> store_result(); 
$stmt -> bind_result($userID);

while($stmt -> fetch()){
    
$url = 'https://api.user.com/api/user/'.$userID.'?key=8aaa03390f0842c6';
    
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$resp = curl_exec($curl);
curl_close($curl);

echo $resp.'<br><br>====================================================<br><br>';

}

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