如何从CURL响应中提取所需数据?

时间:2015-04-01 07:46:02

标签: php curl

这是我得到的回应。我只想提取 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" 
}

5 个答案:

答案 0 :(得分:3)

这只是一个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

答案 1 :(得分:1)

你得到的回应是JSON。

要在PHP中使用它,您需要json_decode它。

这将返回一个带有json响应数据的对象。

代码是

//getData
$obj = json_decode($jsonString);
echo $obj->access_token; //Will echo out the value

答案 2 :(得分:0)

响应采用JSON格式:http://json.org

JSON(Javascript Object Notation)是一种特殊的键/值格式,可用于Javascript和服务器端之间的HTTP请求或Payload共享。

我认为您必须使用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调试非常有用。

如果您需要帮助,请告诉我! ;)

答案 3 :(得分:0)

您可以使用像JSON Viewer, formatter and validator这样的多合一JSON工具从网址加载JSON数据,从桌面上传文件或将JSON数据复制并粘贴到工具中。该工具还将验证,格式化和缩小JSON数据。

答案 4 :(得分:0)

您的问题是指curl(我假设您的意思是命令行工具),但您的帖子被标记为php问题。后一部分已经得到解答,但是您可能仍需要命令行版本(使用jq):

curl "https://<your-url>" | jq '{ .access_token }'
相关问题