2015-04-01 45 views
0

這是我得到的迴應。我只是想提取access_token。我怎樣才能做到這一點。請幫忙。如何從CURL響應中提取所需的數據?

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

回答

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

你得到的響應是JSON。

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

這將返回一個包含json響應數據的對象。

的代碼將是

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

的響應是對JSON格式:http://json.org

JSON(JavaScript對象符號)是一個特殊的鍵/值格式上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調試是非常有用的。

讓我知道你是否需要幫助! ;)

0

您可以使用諸如JSON Viewer, formatter and validator之類的所有JSON工具從URL加載JSON數據,從桌面上載文件或將JSON數據複製並粘貼到工具中。該工具還將驗證,格式化和縮小JSON數據。

+0

我認爲這個問題是有關提取了'訪問token'編程,你並不需要一個工具來手動提取「訪問令牌」 – 2015-04-07 12:29:17

0

你的問題是指捲曲(我假設你的意思是命令行工具),但你的帖子被標記爲一個PHP問題。後半部分已經回答了,但也許你仍然需要(使用jq)的命令行版本:

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