
本文详解 PHP 操作 JSON 文件时因拼写错误导致的致命错误,重点解决将 json_encode() 误写为 $json_encode() 引发的“undefined variable”和“value of type null is not callable”问题,并提供完整、安全的 JSON 增量写入实践方案。
本文详解 php 操作 json 文件时因拼写错误导致的致命错误,重点解决将 `json_encode()` 误写为 `$json_encode()` 引发的“undefined variable”和“value of type null is not callable”问题,并提供完整、安全的 json 增量写入实践方案。
在 PHP 中向 JSON 文件追加或更新数据是常见需求,但初学者极易因函数名拼写疏忽引发严重运行时错误。如题所示,代码第 16 行出现:
file_put_contents('todo.json', $json_encode($jsonArray, JSON_PRETTY_PRINT));此处 $json_encode 被解析为一个变量(而非函数),而该变量未定义,因此触发:
- Warning: Undefined variable $json_encode
- Fatal error: Value of type null is not callable
✅ 正确写法应为调用内置函数 json_encode()(无 $ 符号):
file_put_contents('todo.json', json_encode($jsonArray, JSON_PRETTY_PRINT));但仅修正拼写仍不够健壮。以下是推荐的生产就绪型 JSON 写入流程,包含错误处理与数据安全措施:
立即学习“PHP免费学习笔记(深入)”;
✅ 完整修复版代码(含防御性编程)
<?php
$todoname = $_POST['todoname'] ?? '';
$todoname = trim($todoname);
if ($todoname === '') {
http_response_code(400);
echo "Error: Todo name cannot be empty.";
exit;
}
// 1. 读取并验证 JSON 文件
$jsonFile = 'todo.json';
if (!file_exists($jsonFile)) {
$jsonArray = [];
} else {
$jsonContent = file_get_contents($jsonFile);
if ($jsonContent === false) {
die("Error: Failed to read $jsonFile");
}
$jsonArray = json_decode($jsonContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die("Error: Invalid JSON in $jsonFile");
}
}
// 2. 更新数据(避免重复键,支持去重逻辑)
if (!isset($jsonArray[$todoname])) {
$jsonArray[$todoname] = ['completed' => false];
} else {
// 可选:更新时间戳或忽略重复项
$jsonArray[$todoname]['updated_at'] = date('c');
}
// 3. 安全写入(使用 LOCK_EX 防止并发冲突)
$encoded = json_encode($jsonArray, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
if ($encoded === false) {
die("Error: Failed to encode JSON — " . json_last_error_msg());
}
if (file_put_contents($jsonFile, $encoded, LOCK_EX) === false) {
die("Error: Failed to write to $jsonFile");
}
echo "Success: '$todoname' added to todo.json";
?>⚠️ 关键注意事项
- 永远不要信任用户输入:对 $_POST['todoname'] 进行 trim() 和空值校验,必要时增加 htmlspecialchars() 或正则过滤(如仅允许字母、数字、短横线)。
- JSON 文件权限:确保 Web 服务器进程对 todo.json 有读写权限(如 chmod 644 todo.json),但切勿设为 777。
- 并发安全:使用 LOCK_EX 参数防止多请求同时写入导致数据丢失。
- 编码一致性:添加 JSON_UNESCAPED_UNICODE 确保中文等 Unicode 字符正确保存。
- 调试技巧:开发阶段可临时启用 error_reporting(E_ALL); ini_set('display_errors', 1); 快速定位问题。
掌握 json_encode() 的正确调用方式只是起点;构建可靠的数据持久层,需兼顾健壮性、安全性与可维护性。从一次拼写错误出发,理解 PHP 函数调用机制与文件 I/O 最佳实践,正是进阶的关键一步。











