JSON到HTML表

时间:2013-08-22 03:25:02

标签: php html json

所以在我开始之前,我想说我只知道基本的HTML和CSS。 现在已经不在了,我在http://eu.bitswit.ch/api/server_leaderboard.php?server=71有一个JSON输出,我想把它放到HTML表中。 我在Google / Youtube上环顾四周,但没有一个能够帮助我。

[{"nickname":"|Gates|Domon","steam_id":"STEAM_0:1:8647245","kills":379,"deaths":175,"suicides":0,"tks":5,"score":4590},{"nickname":"Ambassador Pineapple","steam_id":"STEAM_0:1:5287117","kills":372,"deaths":127,"suicides":0,"tks":2,"score":4500},{"nickname":"Clayton","steam_id":"STEAM_0:1:57875311","kills":307,"deaths":118,"suicides":0,"tks":6,"score":3595},{"nickname":"Fluffy Penguin","steam_id":"STEAM_0:1:40834109","kills":205,"deaths":136,"suicides":0,"tks":5,"score":1620},

2 个答案:

答案 0 :(得分:1)

json示例来自问题中的网址:http://eu.bitswit.ch/api/server_leaderboard.php?server=71

{"query":"71","response":0,"query_time":"402.04ms","data":[{"nickname":"Gates Domon","steam_id":"STEAM_0:1:8647245","kills":380,"deaths":175,"suicides":0,"tks":5,"score":4595}]}  

$json = file_get_contents(' http://eu.bitswit.ch/api/server_leaderboard.php?server=71'); // this WILL do an http request for you
    $data = json_decode($json, true);
    $array = $data['data'];
    $table = "<table cellpadding='5'>
<thead>
    <th>nickname</th>
    <th>steam_id</th>
    <th>kills</th>
    <th>deaths</th>
    <th>suicides</th>
    <th>tks</th>
    <th>score</th>
 </thead>
 <tbody>";
    foreach ($array as $value) {
        $table .="<tr>
<td>{$value['nickname']}</td>
<td>{$value['steam_id']}</td>
<td>{$value['kills']}</td>
<td>{$value['deaths']}</td>
<td>{$value['suicides']}</td>
<td>{$value['tks']}</td>
<td>{$value['score']}</td>
</tr>";
    }
    $table .="</tbody></table>";

    echo $table;

答案 1 :(得分:0)

我会使用这样的东西(你需要某些版本的jQuery才能使用这个代码):

if (data.length > 0) {
    var $table = $("<table/>", { "class": "myTable" }).appendTo(document);

    var $headRow = $("<tr/>", { "class": "myHeadRow" }).appendTo($table);
    for (var val in data[0]) {
        var $headCell = $("<td/>", {
            "class": "myHeadCell",
            "text": val
        }).appendTo($headRow);
    }

    for (var i = 0; i < data.length; i++) {
        var $row = $("<tr/>", { "class": "myRow" }).appendTo($table);
        for (var val in data[i]) {
            var $cell = $("<td/>", {
                "class": "myCell",
                "text": data[i][val]
            }).appendTo($row);
        }
    }
}

但请注意,这不是很快的方法。我建议你在你的服务器上获取JSON,然后从PHP或C#代码或其他任何内容中使用JSON,然后只显示渲染表。 当网页加载速度取决于客户端的计算能力时,网络中的基调是不好的。