簡體   English   中英

Json_decode不起作用

[英]Json_decode is not working

我可以看到我的json格式的響應,但是一旦我嘗試解碼並打印特定值,它就會變得無聲而不會輸出錯誤/ null。 嘗試了幾乎所有方法來訪問json。錯誤報告處於啟用狀態

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true); // without true tried
echo $response; //prints json response
echo $result->count; // does not work here $result['count'] tried

JSON響應如下:

{"status":200,"message":"data found","data":{"count":"1050"}}

您可以執行以下操作來獲取單個值,

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $result['status'] . "<br />";  // 200
echo $result['message'] . "<br />"; // data found
echo $result['data']['count'] . "<br />";  // 1050

輸出:

200
data found
1050

在json_decode()中,您通過將2nd參數設置為true來告訴函數創建關聯數組而不是對象。 要使其成為對象,只需使用:

$result = json_decode($response);

否則,使用當前的方法,您可以使用$ result ['count'];訪問變量。

當TRUE將返回的對象將轉換為關聯數組時,json_decode函數具有布爾值。 因此,如果您想使用對象而不是數組,請刪除TRUE

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response);
echo $response; //prints json response
echo $result->count; // should work

或者您可以使用數組代替對象

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $response; //prints json response
echo $result['count'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM