【问题标题】:How to write a json file log, into a html table如何将 json 文件日志写入 html 表
【发布时间】:2014-01-30 11:57:42
【问题描述】:

这是我在 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);

【问题讨论】:

  • 你遇到了什么错误
  • 您的 JSON 无效
  • 那不是 JSON,它是一堆连接在一起的 JSON 文本。我不想尝试解开它(尽管如果你不断地从它上拉出标记并尝试解析它们直到你得到匹配然后循环,你可能会有一些运气)
  • 我有一个空表,控制台上没有错误。
  • 你得到一个空表,因为json_decode() 失败并返回 false

标签: php html json file


【解决方案1】:

日志文件中的 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);

这应该可行。

【讨论】:

  • 嗯,我需要的是一个更好的json文件,并在json_decode中添加“true”。
猜你喜欢
  • 2013-11-26
  • 2014-10-07
  • 1970-01-01
  • 2012-04-06
  • 2023-03-31
  • 2020-01-02
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多