开发者

replacing a single line of a .txt file using php

开发者 https://www.devze.com 2023-04-09 08:05 出处:网络
I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information.The problem is that if I use fwrite once ge开发者_运维知识库tting to the

I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information. The problem is that if I use fwrite once ge开发者_运维知识库tting to the correct line, it leaves any previous information which is longer than the replacement information untouched at the end. Is there an easy way to clear a single line in a .txt file with php that I can call first? Example of what is happening - let's say I'm storing favorite composer, and a user has "Beethoven" in their .txt file, and want's to change it to "Mozart", when I used fwrite over "Beethoven" with "Mozart", I am getting "Mozartven" as the new line. I am using "r+" in the fopen call, as I only want to replace a single line at a time.


If this configuration data doesn't need to be made available to non-PHP apps, consider using var_export() instead. It's basically var_dump/print_r, but outputs the variable as parseable PHP code. This'd reduce your code to:

include('config.php');
$CONFIG['musician'] = 'Mozart';
file_put_contents('config.php', '<?php $CONFIG = ' . var_export($CONFIG, true));


This is a code I've wrote some time ago to delete line from the file, it have to be modified. Also, it will work correctly if the new line is shorter than the old one, for longer lines heavy modification will be required.

The key is the second while loop, in which all contents of the file after the change is being rewritten in the correct position in the file.

<?php
$size = filesize('test.txt');
$file = fopen('test.txt', 'r+');
$lineToDelete = 3;
$counter = 1;

while ($counter < $lineToDelete) {
   fgets($file); // skip
   $counter++;

}

$position = ftell($file);
$lineToRemove = fgets($file);
$bufferSize = strlen($lineToRemove);
while ($newLine = fread($file, $bufferSize)) {
   fseek($file, $position, SEEK_SET);
   fwrite($file, $newLine);
   $position = ftell($file);
   fseek($file, $bufferSize, SEEK_CUR);

}
ftruncate($file, $size - $bufferSize);
echo 'Done';
fclose($file);
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消