问题描述
我从 API 收到的 JSON 字符串
{"accesstokenResponse":{"token":"562371e99fda4296a380547cb5bf9fab","token_type":"Bearer","expires_in_seconds":"77476","client_id":"LTcyMDI1NDI0OQ==","responseStatus":{"code":"100000","message":"Service operation completed successfully","messageDetails":"Access token assigned."}}}
我想提取的信息
562371e99fda4296a380547cb5bf9fab //-->The Token
我的尝试
<?PHP
$user = "LTcyMDI1NDI0OQ==";
$password = "MjAzMDI5MTU";
$returnFormat = "json";
$url = "https://sandBox.dhlecommerce.asia/rest/v1/OAuth/Accesstoken?clientId=".$user.
"&password=".$password."&returnFormat=".$returnFormat."";
$method = "GET";
$headers = array(
"content-type: application/json",);
$curl = curl_init();
curl_setopt_array($curl,array(
CURLOPT_RETURNTRANSFER => true,CURLOPT_URL => $url,CURLOPT_CUSTomrEQUEST => $method,CURLOPT_HTTPHEADER => $headers,));
$response = curl_exec($curl);
$err = curl_error($curl);
$result = json_decode($response);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $result->token;
}
?>
输出:
Warning: Undefined property: stdClass::$token in C:\xampp\htdocs\Tracking\getToken.PHP on line 31
我收到的 JSON 字符串格式错误吗?
我参考的帖子: How do I extract data from JSON with PHP?
解决方法
token
在 accessTokenResponse
对象中,所以:
echo $result->accessTokenResponse->token;