在foreach循环中执行php curl



我试图通过用户ID参数每次只返回一个用户数据的url获得用户数据列表,但要获得一个用户数据,我需要更改url内的用户ID参数。在这种情况下,我想在foreach循环中使用curl来获取所有数据,而不需要每次更改user ID参数。

在我的php脚本,我试图得到所有的用户数据一次使用,但我知道,这不是正确的方式来做到这一点,在我的研究在这里,我发现了一些类似的问题,使用foreach执行curl,但不幸的是,我没有找到一个正确的方法来解决这个问题:

  1. 在foreach-loop (php)中使用cURL

  2. PHP数组cURL foreach

  3. curl在foreach循环内执行php

  4. JSON cURL - 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放入中,但这不是正确的方法。在这种情况下,我怎么能得到所有的数据通过url使用curl在php foreach?

我找到了解决疑问的办法。正如@Barmar在他的评论中提到的,我修改了我的脚本,使用内的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>';
}

最新更新