gpt4 book ai didi

php - 如何将 JSON 字符串转换为 PHP 变量?

转载 作者:行者123 更新时间:2023-12-04 15:52:54 25 4
gpt4 key购买 nike

我试图使用 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) "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd97929593999298bd9a909c9491d39e9290" rel="noreferrer noopener nofollow">[email protected]</a>"
["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);



?>

最佳答案

看起来是一个数组的数组

例如:用户名

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

其他值依此类推

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

关于php - 如何将 JSON 字符串转换为 PHP 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45974230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com