如何使用PHP同时从多个Web服务中获取数据?
发布时间:2020-12-13 22:53:10 所属栏目:PHP教程 来源:网络整理
导读:我有3个网络服务,为我的酒店预订引擎提供数据.如果按顺序运行它会花费太长时间.因此我想使用线程运行它们.但不确定php线程是否支持这个以及它是否安全(因为将处理Web服务的所有3个进程都将读写共享表) 谁能告诉我如何继续? 解决方法 我通常使用以下函数将Si
我有3个网络服务,为我的酒店预订引擎提供数据.如果按顺序运行它会花费太长时间.因此我想使用线程运行它们.但不确定php线程是否支持这个以及它是否安全(因为将处理Web服务的所有3个进程都将读写共享表)
谁能告诉我如何继续? 解决方法
我通常使用以下函数将Simultaneuos HTTP请求发送到Web服务
<?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; } ?> 使用我使用的Web服务 <?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); ?> 希望这可以帮助你:) 另请查看此答案here (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |