首页 > 解决方案 > 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);
}
?>

标签: php

解决方案


无需创建自己需要手动解析的格式,您可以简单地使用 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);

推荐阅读