如何使用 PHP 从文件中解析 JSON 然后提取为 TABLE

How to parse JSON from file using PHP then extract as TABLE

我只是受困于此。我如何使用 PHP.

读取 json 文件

我有 file.json 以下数据样本


[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]

你能给我分享一个 php 代码如何读取 file.json 并将其提取到 html table 吗?

<table>
<tr><td>Firstname</td><td>Lastname</td></tr>
</table>

提前致谢

检查我的 json,因为在您的代码中,名字行中有一个额外的逗号。

试试这个代码:

<?php

$json =  '[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]';

$obj = json_decode($json, true);

echo '<table>
<tr><td>Firstname</td><td>Lastname</td></tr>';

foreach($obj as $key => $value) {
    echo "<tr><td>{$value['firstname']}</td><td>{$value['lastname']}</td></tr>";
}   

echo '</table>';

?>

您可以通过 json_decode();

解码 Json 字符串
<?php 

$jsonStr =  '[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]';

$jsonObj = json_decode($jsonStr,true);

var_dump($jsonObj);

?>