将JSON解析为表格(Wordpress)

3

我希望能够将一些数据从JSON和/或XML解析成表格。

我正在寻求有人帮助我了解此基础知识。我需要将JSON或XML中的多个项目解析到表格中。以下是我的JSON示例:

{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]

我需要帮助将这些数据解析到一个html/Wordpress表中。
我还使用了一种特殊类型的按钮,但如果我能学会正确解析数据,我认为我已经解决了这个问题。
我希望你们中的一些人可以帮助我并指导我正确的方向。我在Google上搜索过,但只找到了解析JSON中一个项目的示例。
1个回答

4
这里有一个示例,展示了如何将这个JSON结构解析成一张表格。
<?php
    $data = json_decode('{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]}');

    // Convert JSON string into a PHP object.
    $appartments = $data->appartments;

    echo('<table>');
    if(!empty($appartments)){
        echo('<thead><tr>');
        // Using the first object to print column names.
        foreach($appartments[0] as $key => $value){
            echo('<th>' . $key . '</th>');   
        }
        echo('</tr></thead>');

        echo('<tbody>');
        // Iterate through all appartments and print them as table cells.
        foreach($appartments as $appartment){
            echo('<tr>');
            foreach($appartment as $key => $value){
                echo('<td>' . $value . '</td>');   
            }
            echo('</tr>');
        }

    echo('</tbody></table>');
    }
?>

Hans,谢谢你的回复。JSON数据在一个URL中。如果URL中包含像我展示的JSON代码中那样的多个项目,是否仍然可以使用相同的方法? - Eric Williams
你可以使用函数 file_get_contents() 来获取文件或 URL 的内容。在我的示例中,您可以在首次加载 JSON 数据 $json = file_get_contents('url-to-json-source-here'); 之前添加一个新行,然后使用 $data = json_decode($json); 进行转换。只要数组中的项目具有相同的结构,它就可以正常工作,否则表格可能会出现问题。 - Hans Westman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接