|
|
- <?php
- // 简易 JSON 存储示例:PHP + JSON 文件
- $dataFile = __DIR__ . '/data.json';
- // 初始化:如果文件不存在,写入一个空数组
- if (!file_exists($dataFile)) {
- file_put_contents($dataFile, json_encode([], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
- }
- $message = '';
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- $name = trim($_POST['name'] ?? '');
- $content = trim($_POST['content'] ?? '');
- if ($name !== '' && $content !== '') {
- // 读取现有数据
- $json = file_get_contents($dataFile);
- $data = json_decode($json, true) ?: [];
- // 追加新数据
- $data[] = [
- 'name' => $name,
- 'content' => $content,
- 'time' => date('Y-m-d H:i:s')
- ];
- // 写回文件
- file_put_contents($dataFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
- $message = '提交成功!';
- } else {
- $message = '昵称和内容不能为空';
- }
- }
- // 读取数据用于展示
- $json = file_get_contents($dataFile);
- $data = json_decode($json, true) ?: [];
- ?>
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <title>JSON 存储示例</title>
- <style>
- body { max-width: 600px; margin: 40px auto; font-family: sans-serif; padding: 0 16px; }
- input, textarea { width: 100%; box-sizing: border-box; padding: 8px; margin: 6px 0; }
- button { padding: 8px 16px; }
- .item { border-top: 1px solid #eee; padding: 10px 0; }
- .item small { color: #999; }
- </style>
- </head>
- <body>
- <h2>JSON 存储示例</h2>
- <?php if ($message): ?>
- <p><?= htmlspecialchars($message) ?></p>
- <?php endif; ?>
- <form method="post">
- <input name="name" placeholder="昵称">
- <textarea name="content" rows="3" placeholder="内容"></textarea>
- <button type="submit">提交</button>
- </form>
- <?php foreach ($data as $row): ?>
- <div class="item">
- <strong><?= htmlspecialchars($row['name']) ?></strong>
- <small><?= htmlspecialchars($row['time']) ?></small>
- <p><?= nl2br(htmlspecialchars($row['content'])) ?></p>
- </div>
- <?php endforeach; ?>
- </body>
- </html>
复制代码
免费提供使用 |
|