File_get_contents()在URL重定向时无法工作

3
我正在使用的函数是:
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

然而,如上所述,该表单包含不同的元素,即代码、月份、日期和年份。

尝试使用curl:让curl跟随重定向? - Antony
如果我没记错的话,这个应该可以工作,因为这里说默认值是跟随重定向,除非达到了max_redirects或超时。 - cryptic ツ
2个回答

4
为什么不使用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
我正在进行一些调整,但看起来它会工作,谢谢! - Lawrence DeSouza

-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
);

 }

什么?据我所见,你所做的只是将第二个参数的布尔值更改为“true”,如果你阅读了文档,那只是切换是否在包含路径中搜索。 - cryptic ツ
感谢 @crypticツ。是的,只有布尔部分有所改变。我已经执行了代码,它运行良好。天气 API 返回了完美的结果。 - Ripa Saha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接