2016-08-16 80 views
1

我正在執行curl請求並獲取返回json響應的響應。以下是回覆後的代碼。如何訪問此json響應中的屬性?

響應: 「零替換真實令牌」

{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1 

代碼中使用(用於測試)和訪問屬性: $ JSON = json_decode($結果); print_r($ json); //打印JSON響應

$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object 
$secondtry = $json['token']; 

echo $firsttry.'<br>';//Code can't continue because of error from $firsttry. 
print_r($secondtry.'<br>');//Nothing Prints at all 

我注意到一個奇怪的異常的地方在最後打印1,在那裏,好像我做

json_encode($json); 

返回響應代替在末尾的一個帶有「true」的字符串 末尾的「1或true」是否會拋出json解碼?

也許我錯過了一些簡單的東西?

的要求全面測試代碼

$url = "https://website.com/restapi.php"; 
//username of the user who is to logged in. 
$userName="adminuser"; //not real user 

$fields_string; //global var 


$fields = array(//array will have more in the future 
'username' => urlencode($userName) 
); 

//url-ify the data for the POST 
foreach($fields as $key=>$value) { global $fields_string; 
$fields_string .= $key.'='.$value.'&'; } 
rtrim($fields_string, '&'); 

//open connection 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_URL,   $url.'?'.$fields_string.'operation=getchallenge'); 
curl_setopt($ch,CURLOPT_POST, count($fields)); 

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

//close connection 
curl_close($ch); 
+0

*「我注意到一個奇怪的異常,它在最後打印出1」*它不是來自'json_encode',它來自* json_encode之後的某個東西*。 –

+0

JSONString結尾的'1'使得這個無效的JSONString – RiggsFolly

+0

所以我會假設在響應結束時使用類似rtim的東西會修復這個問題?讓我嘗試一下。 – DEVPROCB

回答

1

json_decode(),在默認情況下讓子對象爲stdClass對象,而不是數組,除非它們是明確的陣列。

嘗試類似:

$firsttry = $json->result->token; 
+0

默認情況下它沒有這樣做,因爲它看起來像是一個'{'而不是''' – RiggsFolly

+0

因此這個詞明確地說明了('['是json中的一個顯式數組')。 PHP允許你傳遞一個參數給'json_decode()',這將迫使它使用關聯數組而不是'stdClass'對象。 – GentlemanMax

0

後續代碼var_dump顯示你的數據類型。由於result本身就是一個對象,其訪問令牌->而不是[]

$response = '{"success":true...}' 
$json = json_decode($response); //var_dumping this will show you it's an object 
echo $json->result->token; // 000000000 
+0

當運行var轉儲我實際上得到一個NULL。當沒有json解碼的結果上運行vardump時,我得到一個字符串(0)「」 – DEVPROCB

0

我想通了這個問題。在捲曲選項我沒有

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

一旦我把這個@GentelmanMax解決方案爲我,但問題是在捲曲響應直接回應,那裏的返回搬運發回一個字符串,PHP可以使用,然後允許json_decode()按照原樣運行。我知道這很簡單。