PHP-如何在文本文件中写入一行,如果该行在文件中已经可用,则计算请求



我想写一个PHP代码,在文本文件中写一行字符串,如果文本文件中已经有字符串行,那么计算请求,例如文本文件包含:

red.apple:1
big.orange:1
green.banana:1

如果有人请求在文件中添加big.range,如果它在文件中已经可用,则算作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);

如果您仍然需要使用这种格式(比如,这是一些考试测试或遗留问题),请尝试以下功能:

function touchFile($file, $string) {
if (!file_exists($file)) {
if (is_writable(dirname($file))) {
// create file (later)
$fileData = "";
} else {
throw new ErrorException("File '".$file."' doesn't exist and cannot be created");
}
} else $fileData = file_get_contents($file);
if (preg_match("#^".preg_quote($string).":(d+)n#m", $fileData, $args)) {
$fileData = str_replace($args[0], $string.":".(intval($args[1])+1)."n", $fileData);
} else {
$fileData .= $string.":1n";
}
if (file_put_contents($file, $fileData)) {
return true;
} else {
return false;
}
}

最新更新