【问题标题】:How to converts JSON string into a PHP variable?如何将 JSON 字符串转换为 PHP 变量?
【发布时间】:2018-02-08 23:36:21
【问题描述】:

我试图使用 cURL 解析来自 url 的 json 数据,然后使用 json_decode 来访问对象,但我失败了。我已经搜索了如何访问,但我失败了。

这是我访问的链接,希望我能解决问题。

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) "johndoe@gmail.com"
      ["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);



?>

【问题讨论】:

  • 我已经尝试过回显,但它返回数组到字符串的转换

标签: php json curl


【解决方案1】:

当你执行 json_decode($response, true) 并且你使用第二个参数为 true 时,它​​会将它解码为关联数组。

你的 var_dump 也说它是数组。因此,您需要将 $obj 作为数组而不是对象访问

如果要访问用户数组:

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

如果你想访问用户名/br_code:

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

more info about json_decode

【讨论】:

    【解决方案2】:

    json_decode 将 JSON 字符串解码为多维数组 你得到那个错误是因为在 PHP 中对象不是数组 只需使用[] 访问就可以了

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

    【讨论】:

      【解决方案3】:

      您的数据在login 数组中,因此请尝试关注以获取用户的详细信息

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

      【讨论】:

        【解决方案4】:

        似乎是一个数组数组所以

        例如:对于用户名

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

        其他值以此类推

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-26
          • 1970-01-01
          • 2015-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-05
          • 2012-05-21
          相关资源
          最近更新 更多