PHP How can I open several sources using curl?

2019-07-05 16:11发布

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_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);
}

标签: php api url curl
4条回答
三岁会撩人
2楼-- · 2019-07-05 16:15
Explosion°爆炸
3楼-- · 2019-07-05 16:17

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);
    }
 }
查看更多
来,给爷笑一个
4楼-- · 2019-07-05 16:27
<?
$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);
}
?>
查看更多
我只想做你的唯一
5楼-- · 2019-07-05 16:36

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

查看更多
登录 后发表回答