php - PHP - 如果文件中已有行可用,如何在文本文件中写入一行,然后计算请求
问题描述
我想编写一个 PHP 代码,如果该行在文本文件中已经可用,则在文本文件中写入一个字符串行,然后计算例如文本文件包含的请求:
red.apple:1
big.orange:1
green.banana:1
如果有人请求在文件中添加 big.orange,如果它已经在文件中可用,则视为big.orange:2
不可用,然后写入新行big.orange:1
执行后代码文本文件
red.apple:1
big.orange:2
green.banana:1
我编写了以下代码但无法正常工作。
<?PHP
$name = $_GET['fname']
$file = fopen('request.txt', "r+") or die("Unable to open file!");
if ($file) {
while (!feof($file)) {
$entry_array = explode(":",fgets($file));
if ($entry_array[0] == $name) {
$entry_array[1]==$entry_array[1]+1;
fwrite($file, $entry_array[1]);
}
}
fclose($file);
}
else{
fwrite($file, $name.":1"."\n");
fclose($file);
}
?>
解决方案
无需创建自己需要手动解析的格式,您可以简单地使用 json。
下面是关于它如何工作的建议。如果它不存在,它将添加请求的fname
值,如果它不存在,它还将创建文件。
$name = $_GET['fname'] ?? null;
if (is_null($name)) {
// The fname query param is missing so we can't really continue
die('Got no name');
}
$file = 'request.json';
if (is_file($file)) {
// The file exists. Load it's content
$content = file_get_contents($file);
// Convert the contents (stringified json) to an array
$data = json_decode($content, true);
} else {
// The file does not extst. Create an empty array we can use
$data = [];
}
// Get the current value if it exists or start with 0
$currentValue = $data[$name] ?? 0;
// Set the new value
$data[$name] = $currentValue + 1;
// Convert the array to a stringified json object
$content = json_encode($data);
// Save the file
file_put_contents($file, $content);
推荐阅读
- javascript - 如何在javascript中计算结果后加载的元素样式?
- javascript - 在 RxJS 中以块的形式运行一组可观察对象
- javascript - 从 freecodecamp 了解代码的复杂性
- javascript - NodeJS 和 Nginx - 如何打开 url?
- python - 根据值 Pandas 重命名列名
- ruby-on-rails - 如何在rails中按天数或日期名称获取日期?
- angular - 如何在量角器中执行拖放功能
- java - Java for Android 中的自定义对象检测
- reactjs - Firebase 部署命令正在部署一个非常旧的提交
- google-tag-manager - 自定义历史更改触发器以跳过 GTM 中同一页面上的 hashchanges