4 回答

TA貢獻1851條經驗 獲得超3個贊
您可以通過以下方式解碼/解析 JSON 響應:
目的
PHP 關聯數組
對于第二個選項,true使用json_decode()
即您可以使用以下內容:
<?php
const NL = PHP_EOL;
$json = '{
"access_token": "ya29.Il-4B1111",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "1//09uJO5Lo7CFhyCg3333",
"scope": "https://www.googleapis.com/auth/fitness.activity.read https://www.googleapis.com/auth/fitness.location.read"
}';
// object
$jsonObj = json_decode($json);
echo $jsonObj->access_token;
echo NL;
echo $jsonObj->refresh_token;
echo NL;
echo $jsonObj->expires_in;
echo NL;
// associative array
$jsonArr = json_decode($json, true);
echo $jsonArr['access_token'];
echo NL;
echo $jsonArr['refresh_token'];
echo NL;
echo $jsonArr['expires_in'];

TA貢獻1887條經驗 獲得超5個贊
某些 API 以無效的 JSON 響應。出于安全原因,他們在 JSON 對象之后添加了一個布爾表達式(true 或 1)。在解析之前,您可能必須自己預先處理響應。

TA貢獻1943條經驗 獲得超7個贊
我假設您正在為您的日志記錄編碼 $result。之后,您可以使用json_decode($newResult, true)
- 基本上將其轉換為數組,您可以獲得所需的相關值。
https://www.php.net/manual/en/function.json-decode.php

TA貢獻1864條經驗 獲得超6個贊
$url = 'YOUR API URL GOES HERE';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
$json = json_decode($result, true);
print_r($json);
輸出
Array
(
[access_token] => ya29.Il-4B1111
[token_type] => Bearer
//....
)
現在您可以將$json變量用作數組:
echo $json['access_token'];
echo $json['token_type'];
- 4 回答
- 0 關注
- 162 瀏覽
添加回答
舉報