使用PHP的CURL将API的JSON存储到变量中

时间:2014-06-18 16:32:42

标签: php rest curl

我正在尝试将使用以下URL公开的数据存储在PHP变量($ curl_response)中以进行进一步操作,但我当前的代码未正确执行。我已将以下URL中公开的数据复制/粘贴到HTML文件的正文中,并尝试在该HTML文件上运行以下脚本,并且CURL正常工作。我猜这个问题与从这个特定网站正确获取响应有关。也许有一个我忽略的CURL选项。

http://tdm.prod.obanyc.com/api/pullouts/agency/MTABC/list

思想?

<?php 

$ch = curl_init("http://tdm.prod.obanyc.com/api/pullouts/agency/MTABC/list");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($ch);

if ($curl_response === false) {
  $info = curl_getinfo($ch);
  curl_close($ch);
  die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
else echo $curl_response ;

curl_close($ch);

?>

调试输出为:

array('url'=&gt;'','content_type'=&gt; NULL,'http_code'=&gt; 0,'header_size'=&gt; 0,'request_size'=&gt; 0,'filetime'= &gt; -1,'ssl_verify_result'=&gt; 0,'redirect_count'=&gt; 0,'total_time'=&gt; 63.145232,'namelookup_time'=&gt; 0.006015,'connect_time'=&gt; 0,'pretransfer_time'=&gt; ; 0,'size_upload'=&gt; 0,'size_download'=&gt; 0,'speed_download'=&gt; 0,'speed_upload'=&gt; 0,'download_content_length'=&gt; -1,'upload_content_length'=&gt; -1,'starttransfer_time'=&gt; 0,'redirect_time'=&gt; 0,'certinfo'=&gt; array(),'primary_ip'=&gt; '10 .137.36.11','primary_port'=&gt; 80,' local_ip'=&gt;'','local_port'=&gt; 0,'redirect_url'=&gt;'',)在curl exec期间发生错误。 Additioanl信息:

2 个答案:

答案 0 :(得分:0)

问题中的else语句与代码中的语句相同吗?如果是,那么我将首先修复else语句

更改

else $curl_response ;

else
{
   $curl_response; // You might want to echo  $curl_response or store it or do something with it. In it's current state it just does nothing.
}

答案 1 :(得分:0)

我被告知网站的IP地址被阻止,因为服务器不在网络中。这解决了CURL执行时变量的无响应错误和空值。

全部谢谢