用PHP从Json中获取信息

时间:2018-03-18 02:15:23

标签: php json

["{\"account\":{\"username\":\"test\",\"password\":\"hey\",\"info\":{\"ip\":\"193.90.12.119\",\"proxyMethod\":\"TOR\",\"time\":\"2018-03-17 05:32:58\"}}}"]   

您好!我想要做的是从PHP中获取这个Json的用户名。 json存储在一个文件中。虽然我有代码下来从文件中抓取Json。抓住用户名我遇到了很多问题。

我现在拥有什么

<?php
$file = ('/var/www/html/account/generator/accounts.json');
$accountJson = json_decode(file_get_contents($file), true);


echo count($accountJson);
echo $accountJson[0];

echo 'done';
?>

当我尝试通过

抓取用户名时
echo $acountJson[0]['account'];

只有回声{

我已经找了几个小时来解决这个问题。如果有人能帮助我,这将是惊人的。谢谢你提前。

2 个答案:

答案 0 :(得分:0)

在你的情况下$accountJson[0]的内容是一个字符串,你也必须解码它,所以如果你使用这个代码应该工作:

<?php
  $file = ('/Users/cesar/Sites/diversos/teste/accounts.json');
  $accountJson = json_decode(file_get_contents($file), true);

  $stringData = $accountJson[0];

  $data = json_decode($stringData);

  echo $data->account->username;
?>

我在这里测试过并且工作过。

答案 1 :(得分:0)

而不是echo $acountJson[0]['account'];尝试此echo $accountJson[0][account][username];

这是我的JSON文件:

[
  {
    "account":
    {
      "username": "test",
      "password": "hey",
      "info":
      {
        "ip": "193.90.12.119",
        "proxyMethod": "TOR",
        "time": "2018-03-17 05:32:58"
      }
    }
  }
]

PHP文件:

<?php
$file = ('accounts.json');
$accountJson = json_decode(file_get_contents($file), true);

echo $accountJson[0][account][username];


echo '<br>done';

希望这有帮助。