2017-03-08 91 views
-1

我无法获取JSON文件到php数组。JSON到PHP数组错误

我得到了一个json文件作为api的响应(请求用卷曲完成) 并且想要创建一个数组,但它不起作用。

这里是我的代码:

<?php 

class modExpose{ 
public static function getFunction($id){ 

//In my code i am "preparing" the request here 


// *********** cURL 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url.$qry_str); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); 
$response = curl_exec($ch); 
curl_close($ch); 

return $response; 
} 
} 


$id = $_GET['id']; 
$data = modExpose::getFunction($id); 
$array = json_decode($data,true); 
print_r($array); 

?> 

的print_r的功能只提供了:1(不相同的的var_dump()函数)。 我也尝试添加html_entity_decode(),但问题仍然存在。

感谢您的帮助!

+3

json的回应是什么?并检查[json_last_error](http://php.net/json_last_error)的响应 – hassan

+0

我不想在这里发布,因为它包含客户数据,但它是一个有效的json文件,如果我不添加print_r ()或var_dump()在safari末尾显示一个高亮和完美的格式的json文件。 – Philipp

+1

@菲利普,这是一个不提供MVCE的薄弱原因。您可以在维护文件结构的同时将所有的个人身份信息替换为占位符信息。 – HPierce

回答

2

这可能是因为您的curl_exec()调用的返回值为true成功,这就是您从方法返回的所有内容。

如果你想获得,是由卷曲调用返回的数据,您需要设置CURLOPT_RETURNTRANSFER选项:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url.$qry_str); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
// Return the result on success 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); 
// Now response will contain the results of your curl call 
$response = curl_exec($ch); 

除此之外,我假设你已经检查了似乎要取消定义的变量你的示例代码。

+1

非常感谢,这工作! 要花费我多年的时间才能弄清楚。 – Philipp