Get JSON data from many urls via curl_multi

1.1k views Asked by At

Five hours i try to make this code worked:

$url_list = array(
    'https://btc-e.com/api/2/btc_usd/ticker',
    'https://btc-e.com/api/2/btc_eur/ticker',
    'https://btc-e.com/api/2/btc_rur/ticker',
    'https://btc-e.com/api/2/ltc_btc/ticker',
    'https://btc-e.com/api/2/ltc_usd/ticker',
    'https://btc-e.com/api/2/ltc_rur/ticker',
    'https://btc-e.com/api/2/usd_rur/ticker',
    'https://btc-e.com/api/2/eur_usd/ticker',
    'https://btc-e.com/api/2/nmc_btc/ticker',
    'https://btc-e.com/api/2/nvc_btc/ticker',
    'https://btc-e.com/api/2/trc_btc/ticker',
    'https://btc-e.com/api/2/ppc_btc/ticker',
    'https://btc-e.com/api/2/ftc_btc/ticker'
);

function multi_thread_request($nodes){ 
    $mh = curl_multi_init(); 
    $curl_array = array();
    $res = array();

    for($i=0;$i<=12;$i++){
        $curl_array[$i] = curl_init($url_list[$i]); 
        curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true); 
        curl_multi_add_handle($mh, $curl_array[$i]); 
    } 
    $running = NULL; 
    do { 
        //usleep(10000); 
        curl_multi_exec($mh,$running); 
    } while($running > 0); 


    for($i=0;$i<=12;$i++){
        $res[$i] = curl_multi_getcontent($curl_array[$i]);
    } 

    for($i=0;$i<=12;$i++){ 
        curl_multi_remove_handle($mh, $curl_array[$i]); 
    } 
    curl_multi_close($mh);        
    return $res; 
} 
print_r(multi_thread_request($url_list)); 

And it always gives me only array with keys, but with no data. Where is my error?

1

There are 1 answers

1
Sabuj Hassan On BEST ANSWER

Use $nodes instead of $url_list while initializing the curl. Or use global for $url_list inside the function.

$curl_array[$i] = curl_init($nodes[$i]);

Your urls are having https, so add this curl option to handle this.

curl_setopt($curl_array[$i], CURLOPT_SSL_VERIFYPEER, false);

Now it should work like a charm for you!