代码
<?php
// Function to print the first N lines of a file
function printFirstLines($filename, $lines) {
$file = fopen($filename, 'r');
if ($file) {
$lineCount = 0;
while (!feof($file) && $lineCount < $lines) {
echo fgets($file);
$lineCount++;
}
fclose($file);
} else {
echo "Error opening the file.";
}
}
function updateFileContent($filename, $content) {
$file = fopen($filename, 'a'); // 'a' mode appends to the file
if ($file) {
fwrite($file, $content); // Add a new line
fclose($file);
echo "Content has been updated/added to the file.";
} else {
echo "Error opening the file.";
}
}
// Example usage:
// (i) Print the first 5 lines of a file
echo "Printing the first 5 lines of the file:<br>";
printFirstLines("example.txt", 5);
// (ii) Update/Add content to a file
$newContent = "<br>This is a new line added at " . date("Y-m-d H:i:s");
echo "<br>Updating the file with new content:<br>";
updateFileContent("example.txt", $newContent);
?>
输出如下:
Printing the first 5 lines of the file:
He raced to the grocery store. He went inside but realized he forgot his wallet. He raced back home to grab it. Once he found it, he raced to the car again and drove back to the grocery store.
Updating the file with new content:
Error opening the file.
如您所见,printFirstLines 函数工作正常。但在 updateFileContent 中,如果条件失败。我尝试了写入模式和附加模式,但只有在读取模式下才会打开,否则会失败。到底是什么问题,是浏览器不允许写入该文件夹或 smtg 其他吗?
我试图读取文件的几行,然后将一行追加到文件中,我能够读取几行,但在追加模式下打开文件时,代码不起作用,if 条件将变为 false 并显示打开文件时出错
我认为问题可能与文件权限或服务器配置有关,而不是 PHP 代码本身的问题。