2017-03-08 50 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