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

在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);
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题