2011-04-27 56 views
1

我只是想獲取雅虎網頁。 www.yahoo.com使用curl從本地主機

如果我從我的託管網站運行我的簡單腳本,它可以工作。

如果我嘗試從我的本地主機。我得到的是一個頭迴應: 「w32.fp.re1.yahoo.com未壓縮/分塊週三4月27日15點13分48秒PDT 2011」

這裏是我的代碼:

<?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; 
} 


print curl_download('http://www.yahoo.com/'); 
?> 
+3

什麼是你的代碼看起來喜歡? – nlaq 2011-04-27 22:33:11

+0

如果您包含源代碼將會很有幫助。 – 2011-04-27 22:34:11

+0

我們可以幫助你,如果你的一些代碼:) – fedmich 2011-04-27 22:39:00

回答

1

其實,結果開始於

HTTP/1.1 302 Found 

這意味着有一個Location標題在那裏。還有就是:

Location: http://nl.yahoo.com/?p=us 

這僅僅是響應正文:

<!-- w20.fp.ird.yahoo.com uncompressed/chunked Wed Apr 27 17:08:09 PDT 2011 --> 

你需要告訴捲曲跟隨位置標頭。而已。

選項的名稱是CURLOPT_FOLLOWLOCATION。其設置爲true:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

PS
以下1 Location頭後,這是響應主體的開始,當我運行代碼+ FOLLOWLOCATION:

<!DOCTYPE html> 
<html lang="nl-NL" class="y-fp-bg y-fp-pg-grad bkt732"> 
+0

我實際上得到一個200行, 302重定向。 – airnet 2011-04-28 08:46:02

+0

如果你得到我得到的答覆(我的第三個代碼塊),你會得到一個302.那件(你稱之爲頭文件)不是頭文件,而是響應體。我在測試中使用了你的**精確**代碼。 – Rudie 2011-04-28 15:32:28