dqnrk44682 2018-11-03 13:38
浏览 199
已采纳

在Curl请求中传递URL数组

I need to pass multiple url parameters to make a single CURL request. Not sure but whenever I use foreach loop it make calls only on the last url.

Here is my code

$urls = array(
  'https://example.com?id=346428437&league_id=35',
  'https://example.com?id=346428437&league_id=36',
  'https://example.com?id=346428437&league_id=37',
  'https://example.com?id=346428437&league_id=38',
  'https://example.com?id=346428437&league_id=39',
  'https://example.com?id=346428437&league_id=40'
);
foreach($urls as $uri){
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch) or die(curl_error($ch));
if ($data === false) {
    $info = curl_getinfo($ch);
    curl_close($ch);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
 }
curl_close($ch);
}

It appears to call only the last url.

  • 写回答

1条回答 默认 最新

  • duanluanhui8348 2018-11-03 14:06
    关注

    You need to keep a list of the data being passed back, at the moment you are just keeping the last one and overwriting it ($data is always set from curl_exec()). Start by creating an empty array and add to it each time...

    $output = [];    // Empty array
    foreach($urls as $uri){
        $ch = curl_init($uri);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch) or die(curl_error($ch));
        if ($data === false) {
            $info = curl_getinfo($ch);
            curl_close($ch);
            die('error occured during curl exec. Additioanl info: ' . 
                         var_export($info));
        }
        $output [] = json_decode($data,true);   // Add new data to output
        curl_close($ch);
    }
    
    print_r($output);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?