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


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

这似乎是一个简单的任务,但我不能让它工作。

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

所以,我试图使用file_get_contents()以及stream_context_create()来发布我需要的参数并打开结果页面,这样我就可以使用它了。

我尝试了几种不同的方法(首先我使用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)
?>

我错过了什么?我注意到,如果发送错误的参数,页面实际上没有返回任何内容(正如您可以通过简单地打开http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries看到的,没有任何post数据:没有返回任何内容),因此我不确定post是否成功,但没有返回任何内容,因为一些参数是错误的,或者如果代码是错误的。

发布的数据应该是好的,因为我直接从我手工制作的成功查询中复制了它们。我错过了什么?

多亏了CBroe的建议,我们发现cURL是更好的方法。

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

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