Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How can I open several sources using curl?

Tags:

url

php

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_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);
}
like image 211
Vera Avatar asked Nov 25 '25 09:11

Vera


2 Answers

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

like image 93
swordfish Avatar answered Nov 26 '25 22:11

swordfish


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/

like image 28
DhruvPathak Avatar answered Nov 26 '25 22:11

DhruvPathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!