Php:从外部服务上发布的表单获取响应

Php: get response from a posted form on an external service

这似乎是一项简单的任务,但我无法让它发挥作用。

我需要访问墨西哥银行公开提供的一些数据。数据可通过您可以在 link 找到的表格获得:http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarCuadro&idCuadro=CP5&locale=es 您可以通过单击左上部分的按钮 "html" 来查看我需要的数据示例。打开 table 后,我知道如何获取我需要的数据并使用它们。但是,我希望将其作为一项自动化任务,以便脚本可以在新数据可用时定期检查。

所以,我正在尝试使用 file_get_contents() 和 stream_context_create() 来 post 我需要的参数并打开结果页面,所以我可以使用它.

我尝试了几种不同的方法(首先我使用的是 http_post_fields() ),但似乎没有任何效果。 现在我的代码是这样的:

<?php
$url = 'http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries';
$data = array(
'anoFinal' => 2015,
'anoInicial' => 2015,
'formatoHTML.x' => 15,
'formatoHTML.y' => 7,
'formatoHorizontal' => false,
'idCuadro' => 'CP5',
'locale' => 'es',
'sector' => 8,
'series' => 'SP1',
'tipoInformacion' => '',
'version' => 2
);

$postdata = http_build_query($data);

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata
  )
 );

$context  = stream_context_create($opts);

$result = file_get_contents($url, false, $context);

//returns bool(false)
?>

我错过了什么?我注意到如果发送了错误的参数,该页面实际上 return 什么都不做(正如您只需打开 http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries 就可以看到的,没有任何 post 数据:什么都没有 returned) ,因此我不确定 post 是否成功,但没有 returned 因为某些参数错误,或者代码错误。

posted 数据应该没问题,因为我直接从我手动进行的成功查询中复制了它们。 我错过了什么?

事实证明,cURL 是一种更好的方法,感谢 CBroe 的建议。

这是我正在使用的固定代码,如果其他人需要它:

<?php
//$url and $data are the same as above

//initialize cURL
$handle = curl_init($url);

//post values
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);

//set to return the response
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

//execute
$response = (curl_exec( $handle ));
?>