【问题标题】:How to use curl PHP in loop with 100 time? [closed]如何在循环中使用 curl PHP 100 次? [关闭]
【发布时间】:2016-12-22 09:51:35
【问题描述】:

如何在循环中使用 curl 100 次发送请求并将响应存储在数组中?

例如:当 curl 第一次使用 in 循环并获取 500 条记录并存储在一个数组中时,再次使用第二个循环执行相同的过程并从响应中获取 500 条记录并存储在同一个数组中,没有任何问题。最后,我需要在数组中存储 50K 条记录,并将用于在我的数据库中插入记录。

我在过去 2 天工作,但没有得到任何解决方案,所以请帮助我。

<?php
$final_data = array();
for($d=1;$d<=100;$d++)
{   
    $data = '{"request": {"header": {"username": "xxx","password": "xxx"},
    "body": {
    "shapes": [],
    "size_to": "",
    "size_from": "",
    "color_from": "",
    "color_to": "",
    "clarity_from": "",
    "clarity_to": "",
    "cut_from": "",
    "cut_to": "",
    "polish_from": "",
    "polish_to": "",
    "symmetry_from": "",
    "symmetry_to": "",
    "labs": [],
    "price_total_from": "",
    "price_total_to": "",
    "page_number": "1",
    "page_size": "50",
    "sort_by": "price",
    "sort_direction": "ASC"
    }}}';

    $json = json_decode($data,true);
    $json['request']['body']['page_number'] = $d;
    $data = json_encode($json); 

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    curl_setopt($curl, CURLOPT_URL, 'http://technet.rapaport.com/HTTP/JSON/RetailFeed/GetDiamonds.aspx');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    $dd = json_decode($result,true);

    foreach($dd['response']['body']['diamonds'] as $key)
    {       
        array_push($final_data,$key);
    }   
    curl_close($curl);
}
?>

【问题讨论】:

  • 浏览器崩溃与你的服务器端代码有什么关系?您还需要提供更多详细信息、代码等,以便任何人了解您在做什么。
  • 这需要多长时间?浏览器不会等待几分钟,直到服务器端进程完成。客户很可能只是看到“糟糕,超时”或类似的东西。
  • 抱歉我的问题无效,我已经更新了我的问题。

标签: php arrays curl


【解决方案1】:

你可以使用curl_multi,当有多个请求要执行时效率更高。

$mh = curl_multi_init();
$handles = array();

for($i = 0 ; $i < 100 ; $i++){
    $ch = curl_init();
    $handles[] = $ch;

    curl_setopt($ch, CURLOPT_URL, 'http://technet.rapaport.com/HTTP/JSON/RetailFeed/GetDiamonds.aspx');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_multi_add_handle($mh,$ch);
}

$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running);

foreach($handles as $ch){
    $result = curl_multi_getcontent($ch);

    $dd = json_decode($result,true);

    foreach($dd['response']['body']['diamonds'] as $key){       
        array_push($final_data,$key);
    }   

    curl_multi_remove_handle($mh, $ch);
    curl_close($ch);
}

【讨论】:

  • 令人兴奋的解决方案@vincenth。非常感谢。我没有声誉分数,所以我无法给你评分。
  • 没关系,只要对你有帮助。
  • 谢谢@vincenth
  • 拯救了我的一天!感谢您提供此解决方案。
猜你喜欢
  • 2021-12-11
  • 2013-06-07
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 2020-06-05
  • 2021-09-06
  • 2020-12-29
  • 2020-10-19
相关资源
最近更新 更多