2017-08-31 90 views
2

我想使用cURL解析來自url的json數據,然後使用json_decode來訪問這些對象,但是我失敗了。我已經搜索如何訪問,但我失敗了。如何將JSON字符串轉換爲PHP變量?

這是我訪問過的鏈接,希望我能解決問題。

http://www.dyn-web.com/tutorials/php-js/json/decode.php 
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode 
https://stackoverflow.com/questions/20193575/fetch-json-data-using-php 
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode 
https://stackoverflow.com/questions/4433951/decoding-json-after-sending-using-php-curl 

這是var_dump($ obj)的結果;

array(1) { 
    ["login"]=> 
    array(2) { 
    ["error"]=> 
    bool(false) 
    ["user"]=> 
    array(5) { 
     ["br_code"]=> 
     int(0) 
     ["mem_id"]=> 
     int(202) 
     ["username"]=> 
     string(8) "johndoe" 
     ["email"]=> 
     string(33) "[email protected]" 
     ["created_at"]=> 
     string(19) "2017-08-07 15:35:39" 
    } 
    } 
} 

,這是我的PHP代碼

<?php 
session_start(); 

$ch = curl_init('http://localhost/sample/login.php'); 

$username= $_SESSION["USERNAME"]; 
$password= $_SESSION["PASSWORD"]; 

$credentials = [ 
    'username' => $username, 
    'password' => $password 
]; 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials); 
curl_setopt($ch, CURLOPT_USERNAME, "{$username}:{$password}"); 
// execute! 
$response = curl_exec($ch); 
// close the connection 
curl_close($ch); 

$obj= json_decode($response, true); 

// echo $obj; // Notice: Array to string conversion in 

// echo $obj[0]; // Undefined offset 

// echo $obj->user; //Trying to get property of non-object in 

var_dump($obj); 



?> 
+0

我已經嘗試回顯,但它返回數組到字符串轉換 – Novice

回答

3

似乎數組的數組,以便

例如:用戶名

var_dump($obj['login']['user']['username']); 

等爲他人重視

$my_username = $obj['login']['user']['username']); 
1

你的數據在login陣列所以嘗試以下操作以獲得用戶的詳細信息

$user = $obj['login']['user']; 
//to print email 
echo $user['email']; 
//to print username 
echo $user['username']; 
//so on 
0

json_decode解碼JSON字符串轉換成一個多維數組 你得到這個錯誤,因爲PHP對象不是數組 只是訪問[]和你的罰款

$obj['user']['field_requested'] 
1

當你json_decode($響應,真),並且使用的是第二個參數爲真,將其解碼爲關聯數組。

你的var_dump也說它是數組。所以,你需要訪問$ OBJ時數組,如果您要訪問的用戶陣列不反對

$obj['login']['user'] 

如果您要訪問的用戶名/ br_code:

$obj['login']['user']['username']; 
$obj['login']['user']['br_code']; 

more info about json_decode