2013-01-25 53 views
1

我使用的功能是:file_get_contents()函數時獲取URL重定向不工作

function http_post ($url, $data) 
{ 
$data_url = http_build_query ($data); 
$data_len = strlen ($data_url); 
date_default_timezone_set('America/New_York'); 

return array ('content'=>file_get_contents ($url, false 
    , stream_context_create (array ('http'=>array (
    'method'=>'GET', 
    'header'=>"Connection: close\r\nContent-Length: $data_len\r\nContent-type: application/x-www-form-urlencoded\r\n", 
    'content'=>$data_url 
    )))), 
    'headers'=>$http_response_header 
    ); 
} 

和通話是:

http_post('http://www.wunderground.com/cgi-bin/findweather/getForecast/', array('airportorwmo'=>'query','historytype'=>'DailyHistory','backurl'=>"/history/index.html",'code'=>"$myCode",'month'=>"$myMonth",'day'=>"$myDay",'year'=>"$myYear")); 

原來的形式位於下面的頁面上,但我在呼叫中使用表單的操作頁面:

wunderground.com/history/ 

最終我想從重定向頁面獲取內容,它例如:

http://www.wunderground.com/history/airport/CWTA/2013/1/24/DailyHistory.html?req_city=McTavish&req_state=QC&req_statename=Quebec&MR=1 

但是,如上所述,表格採用不同的元素,即代碼,月,日,年。

+0

嘗試捲曲:?使捲曲跟蹤重定向(http://stackoverflow.com/questions/3519939/make-curl-按照重定向) – Antony

+0

這應該工作,如果我沒有被誤認爲[this](http://us3.php.net/manual/en/context.http.php#context.http.follow-location)說默認值將遵循重定向。除非達到'max_redirects',否則超時。 –

回答

-2

嘗試以下功能

function http_post ($url, $data) 
{ 
    $data_url = http_build_query ($data); 
    $data_len = strlen ($data_url); 
    date_default_timezone_set('America/New_York'); 

    return array ('content'=>file_get_contents ($url, true 
, stream_context_create (array ('http'=>array (
'method'=>'GET', 
'header'=>"Connection: close\r\nContent-Length: $data_len\r\nContent-type: application/x-www-form-urlencoded\r\n", 
'content'=>$data_url 
)))), 
'headers'=>$http_response_header 
); 

} 
+0

咦?我所看到的所有操作都是將第二個參數的布爾值更改爲'true',如果您閱讀[documentation](http://us3.php.net/manual/en/function.file-get- contents.php#refsect1-function.file-get-contents-parameters),它只是在包含路徑中切換搜索。 –

+0

謝謝@crypticツ。是的只在布爾部分中改變。我已經執行了代碼,它工作正常。天氣api正在返回完美的結果。 – ripa

3

爲什麼不cURL

function http_post ($url, $data) 
{ 
    $data_url = http_build_query ($data); 
    $data_len = strlen ($data_url); 
    date_default_timezone_set('America/New_York'); 
    $curl = curl_init($url); 
    curl_setopt_array(array(
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_FOLLOWLOCATION => true, 
    )); 

    $content = curl_exec(); 

    curl_close($curl); 

    return array (
     'content' => $content, 
     'headers' => $http_response_header, 
    ); 

} 

而且,你的功能被命名爲post,但你正在做GET要求

+1

我正在做一些調整,但它看起來會起作用,謝謝! –