猿问

如何使用 PHP 解析 Google Fit Json 字符串

我正在尝试解析我从 GoogleFit API 获得的响应。这是我写的片段:


1 $result = curl_exec($ch);//execute post

2 curl_close($ch);//close connection 

3 $newResult = json_encode($result); 

4 Log::info($newResult); 

5 return $newResult;

响应如下所示:


{ "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" } true

第 4 行是 Logging 而不是响应。


true

我想将access_token,refresh_token和存储expires_in在我的db. 我也无法访问响应的属性。请帮忙


哈士奇WWW
浏览 127回答 4
4回答

皈依舞

您可以通过以下方式解码/解析 JSON 响应:目的PHP 关联数组对于第二个选项,true使用json_decode()即您可以使用以下内容:<?phpconst NL = PHP_EOL;$json = '{&nbsp; &nbsp; "access_token": "ya29.Il-4B1111",&nbsp; &nbsp; "token_type": "Bearer",&nbsp; &nbsp; "expires_in": 3600,&nbsp; &nbsp; "refresh_token": "1//09uJO5Lo7CFhyCg3333",&nbsp; &nbsp; "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'];

慕工程0101907

某些 API 以无效的 JSON 响应。出于安全原因,他们在 JSON 对象之后添加了一个布尔表达式(true 或 1)。在解析之前,您可能必须自己预先处理响应。

杨__羊羊

我假设您正在为您的日志记录编码 $result。之后,您可以使用json_decode($newResult, true)- 基本上将其转换为数组,您可以获得所需的相关值。https://www.php.net/manual/en/function.json-decode.php

慕尼黑的夜晚无繁华

$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(&nbsp; &nbsp; 'Content-Type: application/json',&nbsp; &nbsp; 'Accept: application/json'));$result = curl_exec($cURL);curl_close($cURL);&nbsp; &nbsp;$json = json_decode($result, true);print_r($json);输出Array(&nbsp; &nbsp; [access_token] => ya29.Il-4B1111&nbsp; &nbsp; [token_type] => Bearer&nbsp; &nbsp; //....)现在您可以将$json变量用作数组:echo $json['access_token'];echo $json['token_type'];
随时随地看视频慕课网APP
我要回答