2015-10-10 44 views
0

这似乎是一件容易的事,但我无法让它正常工作。Php:从外部服务上发布的表单获得响应

我需要访问墨西哥银行公开提供的一些数据。您可以通过以下链接找到相关数据: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而没有任何发布数据所看到的:没有任何返回内容),因此我不确定该帖子是否成功,但没有返回,因为一些参数错误,或者代码错误。

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

+0

你忘了说明是什么问题。你只是说“不起作用”。 –

+0

那么,因为它返回布尔(假),这显然不是我想要获取的数据。 – DavidTonarini

+1

将''ignore_errors'=> true'添加到您的上下文中,然后查看您获得的内容。此外,执行'var_dump($ http_response_header);'以查看远程服务器是否回答错误代码。 – CBroe

回答

0

事实证明,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)); 
?> 
相关问题