php curl请求_使用cURL在PHP中同时进行HTTP请求

php curl请求

php curl请求

The basic idea of a Web 2.0-style "mashup" is that you consume data from several services, often from different providers and combine them in interesting ways. This means you often need to do more than one HTTP request to a service or services. In PHP if you use something like file_get_contents() this means all the requests will be synchronous: a new one is fired only after the previous has completed. If you need to make three HTTP requests and each call takes a second, your app is delayed at least three seconds.

Web 2.0样式的“混搭”的基本思想是,您可以使用来自多个服务(通常是来自不同提供程序的服务)中的数据,并以有趣的方式对其进行组合。 这意味着您经常需要对一个或多个服务执行多个HTTP请求。 在PHP中,如果使用诸如file_get_contents()之类的东西,则意味着所有请求都将是同步的:只有在前一个请求完成后才触发新请求。 如果您需要发出三个HTTP请求,而每个调用都花费一秒钟,则您的应用程序将延迟至少三秒钟。

(Solution)

An improvement of course is to cache responses as much as possible, but at one point or another you still need to make those requests.

当然,一种改进是尽可能多地缓存响应,但是在某一点或另一点,您仍然需要发出这些请求。

Using the curl_multi* family of cURL functions you can make those requests simultaneously. This way your app is as slow as the slowest request, as opposed to the sum of all requests. And that's something.

使用curl_multi *系列cURL函数,您可以同时发出这些请求。 这样,您的应用与最慢的请求一样慢,而不是所有请求的总和。 就是这样

功能(A function)

Here's a little function I coded that will allow you do multi requests.

这是我编写的一个小功能,可让您执行多个请求。

<?php
 
function multiRequest($data, $options = array()) {
 
  // array of curl handles
  $curly = array();
  // data to be returned
  $result = array();
 
  // multi handle
  $mh = curl_multi_init();
 
  // loop through $data and create curl handles
  // then add them to the multi-handle
  foreach ($data as $id => $d) {
 
    $curly[$id] = curl_init();
 
    $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
    curl_setopt($curly[$id], CURLOPT_URL,            $url);
    curl_setopt($curly[$id], CURLOPT_HEADER,         0);
    curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
 
    // post?
    if (is_array($d)) {
      if (!empty($d['post'])) {
        curl_setopt($curly[$id], CURLOPT_POST,       1);
        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
      }
    }
 
    // extra options?
    if (!empty($options)) {
      curl_setopt_array($curly[$id], $options);
    }
 
    curl_multi_add_handle($mh, $curly[$id]);
  }
 
  // execute the handles
  $running = null;
  do {
    curl_multi_exec($mh, $running);
  } while($running > 0);
 
 
  // get content and remove handles
  foreach($curly as $id => $c) {
    $result[$id] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
  }
 
  // all done
  curl_multi_close($mh);
 
  return $result;
}
 
?>

消费中 (Consuming)

The function accepts an array of URLs to hit and optionally an array of cURL options if you need to pass any. The first array can be a simple indexed array or URLs or it can be an array of arrays where the second has a key named "url". If you use the second way and you also have a key called "post", the function will do a post request.

该函数接受要命中的URL数组,并在需要传递任何URL时接受可选的cURL选项数组。 第一个数组可以是简单的索引数组或URL,也可以是第二个数组具有名为"url"的键的数组。 如果使用第二种方法,并且还有一个名为"post"的键,则该函数将执行发布请求。

The function returns an array of responses as strings. The keys in the result array match the keys in the input.

该函数以字符串形式返回响应数组。 结果数组中的键与输入中的键匹配。

GET示例 (A GET example)

Let's say you want to use some Yahoo search web services (consult YDN) to create a music artist band-o-pedia kind of mashup. Here's how you can search audio, video and images at the same time:

假设您要使用某些Yahoo搜索Web服务(请咨询YDN )来创建音乐艺术家的Band-o-pedia混搭。 您可以通过以下方式同时搜索音频,视频和图像:

<?php
 
$data = array(
  'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json',
  'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Pearl+Jam&output=json',
  'http://search.yahooapis.com/AudioSearchService/V1/artistSearch?appid=YahooDemo&artist=Pearl+Jam&output=json'
);
$r = multiRequest($data);
 
echo '<pre>';
print_r($r);
 
?>

This will print something like:

这将打印如下内容:

Array
(
    [0] => {"ResultSet":{"totalResultsAvailable":"633","totalResultsReturned":...
    [1] => {"ResultSet":{"totalResultsAvailable":"105342","totalResultsReturned":...
    [2] => {"ResultSet":{"totalResultsAvailable":10,"totalResultsReturned":...
)

POST示例 (A POST example)

There's an interesting Yahoo search service called term extraction which analyses content. It accepts POST requests. Here's how to consume this service with the function above, making two simultaneous requests:

雅虎有一个有趣的搜索服务,称为术语提取,可以分析内容。 它接受POST请求。 以下是通过上述功能使用此服务并同时发出两个请求的方法:

<?php
$data = array(array(),array());
 
$data[0]['url']  = 'http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction';
$data[0]['post'] = array();
$data[0]['post']['appid']   = 'YahooDemo';
$data[0]['post']['output']  = 'php';
$data[0]['post']['context'] = 'Now I lay me down to sleep,
                               I pray the Lord my soul to keep;
                               And if I die before I wake,
                               I pray the Lord my soul to take.';
 
 
$data[1]['url']  = 'http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction';
$data[1]['post'] = array();
$data[1]['post']['appid']   = 'YahooDemo';
$data[1]['post']['output']  = 'php';
$data[1]['post']['context'] = 'Now I lay me down to sleep,
                               I pray the funk will make me freak;
                               If I should die before I waked,
                               Allow me Lord to rock out naked.';
 
$r = multiRequest($data);
 
print_r($r);
?>

And the result:

结果:

Array
(
    [0] => a:1:{s:9:"ResultSet";a:1:{s:6:"Result";s:5:"sleep";}}
    [1] => a:1:{s:9:"ResultSet";a:1:{s:6:"Result";a:3:{i:0;s:5:"freak";i:1;s:5:"sleep";i:2;s:4:"funk";}}}
)

        
        

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/

php curl请求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值