【问题标题】:Parsing JSON feed to PHP and then manipluating data?将 JSON 提要解析为 PHP,然后处理数据?
【发布时间】:2012-09-24 17:39:09
【问题描述】:

我有一个私有的 JSON 提要(按 IP 地址),我可以使用命令对其进行解析

$json = file_get_contents("http://#");

这就是提要的样子,并且该命令有效 - 使用 json_decode($json); 时它会正确转储数据;或 json_decode($json,true);我做了一个 var 转储。

    {
    "Holder": [
        {
            "name": "Subholder One",
            "operators": [
        {
          "username": "User1",
          "status": 3
        },
        {
          "username": "User2",
          "status": 3
        },
        {
          "username": "User3",
          "status": 3
        },
        {
          "username": "User4",
          "status": 1
        }
      ]
    },
    {
      "name": "Subholder Two",
      "operators": [
        {
          "username": "User5",
          "status": 3
        }
      ]
    },
    {
      "name": "Subholder Three",
      "operators": [
        {
          "username": "User6",
          "status": 3
        }
      ]
    },
    {
      "name": "Subholder Four",
      "operators": [
        {
          "username": "User7",
          "status": 1
        },
        {
          "username": "User8",
          "status": 3
        },
        {
          "username": "User9",
          "status": 1
        }
      ]
    }
  ]
}

当我使用带有一行数据的简单以下代码时,no file_get_contents 但它可以工作:

$obj = json_decode($json);
echo $obj->username;
echo $obj->status;

当我使用 file_get_contents 时它不起作用。

我想要做的就是显示所有数据的用户名和状态(数字转换为我已经完成的短语),并且单独显示用户名。

例如在用户 1 的个人资料页面上,我想解析他们的“用户名”和“状态”,将状态编号转换为相应的短语并显示在屏幕上。

我在这里摸不着头脑......所以任何帮助都非常感激。

【问题讨论】:

  • 您没有得到有效的 JSON 数据。
  • 在此处粘贴 file_get_contents 结果。也许这个功能不允许通过http获取内容? (php.ini)
  • 你能在 json_decode 之前将你得到的结果粘贴到 file_get_contents 中吗?因为您在上述问题中粘贴的 json 代码是有效的

标签: php parsing json


【解决方案1】:

试试

  $obj = json_decode($json, true);

  echo $obj['username'];
  echo $obj['status'];

【讨论】:

  • 谢谢已经试过了 - 不起作用 :o( 当我手动编码数据时它起作用,从提要中提取它不起作用。
  • 大家好 - 有人帮忙吗?从提要调用时,它仍然不起作用:(
  • PHP echo 不起作用,但 print_r 确实......问题是我希望能够去如果用户名 = User1,然后状态 = 3 单独......即在一组单独的页面上使用相关的用户信息和状态...
【解决方案2】:

试试这个:

$request_url ="http://mysamplefeed.com/";
$requests = file_get_contents($request_url);
$my_response = json_decode($requests);
foreach($my_response->Holder as $item){
'<p>' .$item->username; . '</p>'
'<p>' .$item->status; . '</p>'
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多