在 foreach 循环中执行 php curl

Execute php curl inside foreach looping

我正在尝试通过 url 获取用户数据列表,用户 ID 参数每次 return 只有一个用户数据,但要获取一个用户数据,我需要更改url 中的用户 ID 参数。在这种情况下,我想在 foreach 循环中使用 curl 来获取所有数据,而无需每次都更改用户 ID 参数。

在我的 php 脚本中,我尝试使用 while 一次获取所有用户数据,但我知道这不是正确的方法,并且在这里研究期间,我发现了一些使用 foreach 来执行 curl 的类似问题,但不幸的是我没有找到解决这个问题的正确方法:

  1. PHP Array cURL foreach

  2. curl execution inside foreach loop php

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

下面是 php 脚本,我试图使用 在循环 中获取所有用户数据,我将 curl 放在里面:


// 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>';
    
}


如上所示,我在循环 时将curl 放在 中,但这不是正确的方法。在这种情况下,如何在 php foreach 中使用 curl 通过 url 获取所有数据?

我找到了解决我的疑问的方法。正如@Barmar 在他的评论中提到的,我修改了我的脚本以使用 while loop 中的 curl 从 api url 获取用户信息,如下所示:


//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>';

}