CURL多次

时间:2012-11-27 09:18:27

标签: php curl cron

$hotel_query = "select hotel_id,hotel_name,trip_url,automatic_status from hotels where automatic_status='0'";
$hotel_result = mysql_query($hotel_query) or die(mysql_error());
while($hotel_row = mysql_fetch_object($hotel_result))
{
     $url=$hotel_row->trip_url;
     $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    echo curl_error($ch);
    echo $result;
}

上面的代码是通过php中的cron job运行的。酒店table中有5个trip_url。这意味着curl应该执行5次并从服务器返回结果5次但是 但是当我运行它时,只打印一个结果并停止执行。

1 个答案:

答案 0 :(得分:0)

尝试一下:

<?php

function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }    
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();    
    // Now set some options (most are optional)    
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);    
    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");    
    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");    
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);    
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);    
    // Download the given URL, and return output
    $output = curl_exec($ch);    
    // Close the cURL resource, and free system resources
    curl_close($ch);    
    return $output;
}

$loop_counter = 1;
$hotel_query = "select hotel_id,hotel_name,trip_url,automatic_status from hotels where automatic_status='0'";
$hotel_result = mysql_query($hotel_query) or die(mysql_error());
while($hotel_row = mysql_fetch_object($hotel_result)){
     $url=$hotel_row->trip_url;
    echo "Loop no.".$loop_counter."<br />";
    echo curl_download($url);
    $loop_counter++;
}



?>

CURL代码来自here