开发者

PHP How can I open several sources using curl?

I have some code to get json content of a site1 but I also need to get content of a site2. Should I rewrite all these lines again for the site2? Or maybe I can add one more URL in the curl_setopt?

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,"http://site1.com");
curl_setopt($ch, CURLOPT_RETURNTRA开发者_StackOverflowNSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$outputJson = curl_exec($ch);
if ($outputJson === FALSE) {
    echo 'Sorry, This service is currently unavailable: '. curl_error($ch);
}


You can create a function like

function get_data($url)
{
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL,$url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     $outputJson = curl_exec($ch);
     if ($outputJson === FALSE) {
        echo 'Sorry, This service is currently unavailable: '. curl_error($ch);
     }
     return $outputJson;
 }

and call it with

get_data("http://blah.com");
get_data("http://blah1.com");

This might not be an optimal solution but shuould work for simple instances


You can get better performance with multi url curl. See : http://php.net/manual/en/function.curl-multi-exec.php

And :

http://www.rustyrazorblade.com/2008/02/curl_multi_exec/


You might want to try to loop trought the different site:

 $aSites = array("http://site1.com","http://site2.com");
 for($x=0; $x<count($aSites); $x++){
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL,$aSites[$x]);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     $outputJson = curl_exec($ch);
     if ($outputJson === FALSE) {
        echo 'Sorry, This service is currently unavailable: '. curl_error($ch);
    }
 }


<?
$url1 = "http://site1.com";  
$url2 = "http://site2.com";  

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$outputJson = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, $url2);
$outputJson2 = curl_exec($ch);
curl_close($ch);

if ($outputJson === FALSE || $outputJson2 === FALSE) {
    echo 'Sorry, This service is currently unavailable: '. curl_error($ch);
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜