php读写json文件

PHP Simple Comments Read/Write jSon data to text file

A few days ago i had to build a simple comment form. First i thought about MYSQL etc, but this all seems to be too complicated. So i came up with a simple solution based on jSon and a TXT file.

So that’s how it cooks:

1. Load the text file with the comments and convert it to an array with json_decode

1
2
3
4
5
/* get comments from file */

$commentsText
 =
 file_get_contents
(
'comments.txt'
)
;

 
/* create array list from comments */

$commentsList
 =
 json_decode
(
$commentsText
,
true
)
;

2. Check if a new comment was posted and save to file when valid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* check if new comment is posted and minimum 3 characters are set */

if
(
 !
empty
(
$_POST
[
'comment'
]
)
 &&
 strlen
(
$sComment
)
 >
 3
 )
{

 
        /* get posted comment and remove all HTML */

        $sComment
 =
 strip_tags
(
$_POST
[
'comment'
]
)
;

 
        /* add comment, client IP and date to array */

        $commentsList
[
'comments'
]
[
]
 =
 array
(

                'text'
 =>
 $sComment
,

                'ip'
 =>
 $_SERVER
[
'REMOTE_ADDR'
]
,

                'date'
 =>
 time
(
)

        )
;

 
        /* convert comments to string */

        $commentsText
 =
 json_encode
(
$commentsList
)
;

 
        /* save comment to file */

        file_put_contents
(
$commentsFile
,
 $commentsText
)
;

}

3. Then we can loop the comment list and create HTML for the output

1
2
3
4
5
6
7
8
9
/* create html list */

$commentsHTML
 =
 "<ul>"
;

/* loop all comments */

foreach
(
 $commentsList
[
'comments'
]
 as
 $commentItem
 )
{

        // add comment to html list

        $commentsHTML
.=
 "<li>"
 .
 $commentItem
[
'text'
]
 .
 "</li>"
;

}

/* close html comments list */

$commentsHTML
 .=
 "</ul>"
;

4. Then we add the HTML form and the list with comments

1
2
3
4
5
6
7
<form
 id
=
"comments"
 method
=
"POST"
><form
 id
=
"comments"
 method
=
"POST"
>

    <h1
>
Comments?</
h2
>

    <div
><?=
$errorMessage?></
div
>

    <textarea
 id
=
"comment"
 name
=
"comment"
 cols
=
"70"
>
 </
textarea
><br
/
>

    <input
 type
=
"submit"
 value
=
"yes"
 /
>

    <?=
$commentsHTML?>

</
form
>

I know simple but i thought to share it, you can download the full example including sorting and some more validation stuff, or check out the example page .

### 使用 AJAX 实现 JSON 文件的读取与写入 #### 1. **AJAX 读取 JSON 文件** 通过 AJAX 技术可以从服务器端读取 JSON 数据。通常情况下,JSON 数据会被作为字符串形式返回给客户端,随后可以通过 `JSON.parse()` 将其转换为 JavaScript 对象。 以下是使用原生 XMLHttpRequest 或者 Fetch API 来读取 JSON 文件的例子: ```javascript // 使用 XMLHttpRequest 读取 JSON 文件 var xhr = new XMLHttpRequest(); xhr.open('GET', 'data.json', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var jsonData = JSON.parse(xhr.responseText); // 转换为 JS 对象 console.log(jsonData); } }; xhr.send(); // 使用 Fetch API 读取 JSON 文件 fetch('data.json') .then(response => response.json()) // 自动解析为 JS 对象 .then(data => { console.log(data); }) .catch(error => console.error('Error:', error)); ``` 上述代码展示了两种方式来读取 JSON 文件[^3]。需要注意的是,在实际应用中可能需要处理跨域问题以及错误捕获逻辑。 --- #### 2. **AJAX 写入 JSON 文件** AJAX 并不直接支持向文件写入数据的功能,因为浏览器的安全策略不允许前端脚本直接修改本地文件系统中的内容。因此,要实现 JSON 文件的写入操作,通常需要借助后端技术(如 PHP、Node.js 等)配合完成。 ##### (1)**发送 JSON 数据至后端** 在前端部分,可以将 JSON 数据序列化为字符串并通过 POST 请求传递到后端。 ```javascript // 发送 JSON 数据到后端 var jsonData = { key: "value", number: 123 }; var jsonString = JSON.stringify(jsonData); var xhr = new XMLHttpRequest(); xhr.open('POST', '/save-json.php', true); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log('保存成功:', xhr.responseText); } }; xhr.send(jsonString); // 使用 Fetch API 提交 JSON 数据 fetch('/save-json.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: "value", number: 123 }) }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.error('Error:', error)); ``` 此处的关键在于设置 HTTP 头部字段 `Content-Type` 为 `application/json`,以便告知服务端接收到的数据是一个 JSON 字符串。 --- ##### (2)**后端处理并写入 JSON 文件** 以下分别展示基于不同后端语言的解决方案: ###### a. **PHP 示例** 利用 PHP 可以轻松地追加或者覆盖指定路径下的 JSON 文件内容。 ```php <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $jsonData = file_get_contents('php://input'); // 获取原始输入流 $decodedJson = json_decode($jsonData, true); // 解码成数组 $file = 'data.json'; $currentData = []; if (file_exists($file)) { $currentData = json_decode(file_get_contents($file), true); // 加载现有数据 } $currentData[] = $decodedJson; // 追加新的记录 file_put_contents($file, json_encode($currentData)); // 重新编码并存储回文件 } ?> ``` 此段代码实现了接收来自前端提交的 JSON 数据,并将其追加到现有的 JSON 文件中[^2]。 --- ###### b. **Node.js 示例** 如果采用 Node.js,则可结合内置模块 `fs` 完成类似的文件写入任务。 ```javascript const express = require('express'); const app = express(); const fs = require('fs'); app.use(express.json()); // 中间件用于解析 application/json 类型请求体 app.post('/save-json', (req, res) => { let currentData; try { const rawData = fs.readFileSync('data.json', 'utf8'); currentData = JSON.parse(rawData); // 如果文件存在则加载已有数据 } catch (e) { currentData = []; // 若无初始数据,默认为空数组 } currentData.push(req.body); // 插入新条目 fs.writeFileSync('data.json', JSON.stringify(currentData)); // 更新文件 res.send('保存成功!'); }); app.listen(3000, () => console.log('Server running on port 3000')); ``` 该示例创建了一个简单的 Express 应用来监听 `/save-json` 接口上的 POST 请求,并负责更新对应的 JSON 文件[^4]。 --- ### 总结 综上所述,虽然 AJAX 不具备直接操控文件的能力,但它能够方便地同后端交互从而间接达成目标——即由前端发起网络请求传输所需数据,再依靠后端程序具体实施文件存取动作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值