这是我得到的响应。我只想提取access_token。我该怎么做。请帮忙。
HTTP/1.1 200 OK Via: 1.1 lvqma554 (), 1.1 lvqma554 ()
Transfer-Encoding: chunked
Connection: keep-alive
X-CorrelationID: Id-e41cc17c551ba0be17900000 0; Id-9a8a03a2551ba0be02907400 0
Cache-Control: no-store
Date: Wed, 01 Apr 2015 07:39:42 GMT
Pragma: no-cache
Server: Apache-Coyote/1.1
X-AMEX-DPG-DEPRECATED: No
X-AMEX-DPG-MSG-ID: Id-e41cc17c551ba0be17900000
X-AMEX-DPG-STATUS: Success
Content-Type: application/json;charset=UTF-8
{
"access_token" : "7612126f-dea3-449b-b349-94be115e938a",
"token_type" : "mac",
"expires_in" : 7200,
"refresh_token" : "bc17169d-4fa0-407f-976f-32b2b4ef8812",
"scope" : "card_info",
"mac_key" : "537d3fc2-6a86-456a-b38b-60f77fe79a45",
"mac_algorithm" : "hmac-sha-1"
}
它只是一个json字符串:
$a = '{ "access_token" : "7612126f-dea3-449b-b349-94be115e938a", "token_type" : "mac", "expires_in" : 7200, "refresh_token" : "bc17169d-4fa0-407f-976f-32b2b4ef8812", "scope" : "card_info", "mac_key" : "537d3fc2-6a86-456a-b38b-60f77fe79a45", "mac_algorithm" : "hmac-sha-1" }';
$b = json_decode($a,true);//here the json string is decoded and returned as associative array
echo $b['access_token'];
收益率:
7612126f-dea3-449b-b349-94be115e938a
您得到的响应是JSON。
要在PHP中使用它,您需要对其进行json_decode。
这将返回一个带有json响应数据的对象。
代码将是
//getData
$obj = json_decode($jsonString);
echo $obj->access_token; //Will echo out the value
响应采用JSON格式:http://json.org
JSON(Javascript Object Notation)是一种特殊的键/值格式,适用于Javascript和服务器端之间的HTTP请求或有效负载共享。
我认为你必须使用json_decode来获取数据,但你必须始终检查有效负载响应的形式是否正确
你可以这样做:
$jsonResponse = '{ "access_token" : "7612126f-dea3-449b-b349-94be115e938a", "token_type" : "mac", "expires_in" : 7200, "refresh_token" : "bc17169d-4fa0-407f-976f-32b2b4ef8812", "scope" : "card_info", "mac_key" : "537d3fc2-6a86-456a-b38b-60f77fe79a45", "mac_algorithm" : "hmac-sha-1" }';
//getData
$obj = json_decode($jsonResponse, JSON_NUMERIC_CHECK);
if(! $obj || ! isset($obj->access_token) {
echo "Error with the data.";
} else {
echo $obj->access_token;
}
一般来说,如果你想知道一个字符串是否是有效的JSON,我可以建议使用这个:https://www.jsoneditoronline.org它对JSON调试非常有用。
如果你需要帮助,请告诉我!)
您可以使用一个集所有功能于一身的JSON工具,如JSON Viewer、格式化程序和验证器,从url加载JSON数据,从桌面上传文件,或将JSON数据复制粘贴到该工具中。该工具还将验证、格式化和缩小JSON数据。
您的问题指的是curl(我认为您指的是命令行工具),但您的帖子被标记为php问题。后一部分已经回答了,但也许您仍然需要一个命令行版本(使用jq):
curl "https://<your-url>" | jq '{ .access_token }'