dongshi9526 2014-01-30 11:57
浏览 109
已采纳

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

Here my first question in SO:

I have a simple log.json where are wrote some messages like:

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

So, what I would is to read the content of log.json and put it in a simple html table,

I did like this:

<?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>

Of course doesn't work.. any idea or advise? Thank you guys!

Edit: Here is how i write json in log.json:

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

1条回答 默认 最新

  • dongzhuang6417 2014-01-30 12:22
    关注

    The JSON in your log file is not valid, because a wrapping array and the comma separators are missing between the items. You have to rewrite your write function. Take a look at this quick example:

    <?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);
    

    This should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配