如何将json文件日志写入html表

时间:2014-01-30 11:57:43

标签: php html json file

这是我在SO中的第一个问题:

我有一个简单的log.json,其中写了一些消息,如:

{"name":"Bob","message":"Hey there"}{"name":"Alice","message":"Hi Sir"}

那么,我想读取log.json的内容并将其放在一个简单的html表中,

我确实喜欢这个:

<?php
        session_start();
        if ($_SESSION['me'] == "") {    // Just in case you got a session
            header("location:index.php");
        }

        $logFile = "log.json";
        $data = file_get_contents($logFile);
        $json_data = json_decode($data);
    ?>

    <html>
        <head>
            <title>Message History</title>
        </head>
        <body>
            <table border="1px">
            <tr>
                <td>
                    User
                </td>
                <td>
                    Messages
                </td>
            </tr>
                <?php
                    foreach ($json_data as $row) { 
                ?>
            <tr>
                    <td>
                        <?= $row->name; ?>
                    </td>
                    <td>
                        <?= $row->message; ?>
                    </td>
                <?php
                }           // close my loop
                ?>
            </tr>
        </table>
            <br />
            <input type="button" value="Back Home" onclick="location.href='home.php';">
        </body>
    </html>

当然不起作用..任何想法或建议? 谢谢你们!

编辑: 以下是我在log.json中编写json的方法:

$logFile = "log.json";
            $file = json_encode(array('name'=>$user_name, 'message'=>$user_message));   
            file_put_contents($logFile, $file, FILE_APPEND | LOCK_EX);

1 个答案:

答案 0 :(得分:0)

日志文件中的JSON无效,因为项之间缺少包装数组和逗号分隔符。你必须重写你的写功能。看看这个简单的例子:

<?php

$logFile = "log.json";
$content = array('name'=> "Max", 'message'=> "Test 123");
$existing = json_decode(@file_get_contents($logFile));
if(!$existing || !is_array($existing))
{
    $existing = array();
}
$existing = array_merge($existing, array($content));
file_put_contents($logFile, json_encode($existing), LOCK_EX);

这应该有用。

相关问题