通过PHP脚本从JSON提取文本,其中JSON输入未知

问题描述 投票:0回答:1

下面是用户要输入的JSON,请注意用户可以输入任何JSON格式,我仅举一个例子。

我需要知道如何通过PHP脚本从JSON仅提取文本。请注意,JSON可以是任何形式或类型,如下所示:

{
    "title": "rahul",
    "date": [
        {
            "day": 25,
            "month": "May",
            "year": 2020        }
    ],
    "room": {
        "class": "super",
        "number": 666
    }
}

我需要如下输出:

title rahul
date
day 25
month May
year 2020
room
class super
number 666

我使用了json_decode,但不能正确地提供上述输出。

php json
1个回答
0
投票

json_decode()将是最好的答案,它将解析任何有效的JSON字符串,并返回Object或Array。

鉴于您已经说过您可以具有任何JSON结构,因此我创建了一个递归解决方案,该解决方案将为您提供所要获得的输出:

<?php

$inputJson = <<<JSON
{ "title": "rahul", "date": [ { "day": 25, "month": "May", "year": 2020 } ], "room": { "class": "super", "number": 666 } }
JSON;

if ($decoded = json_decode($inputJson, true)) {
    outputRecursive($decoded);
}

function outputRecursive($data) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            if (!is_int($key)) {
                echo $key . PHP_EOL;
            }

            outputRecursive($value);
        } else {
            echo $key . ' ' . $value . PHP_EOL;
        }
    }
}

控制台输出:

title rahul
date
day 25
month May
year 2020
room
class super
number 666
© www.soinside.com 2019 - 2024. All rights reserved.