This question already has answers here:
Is this the most efficient way to get and remove first line in file?
(12 answers)
Closed 6 years ago.
I try to make a simple php to read and delete first line from a text file.
So far I got the code:
<?php
$myfile = fopen("text.txt", "r") or die("Unable to open file!");
$ch=1;
while(!feof($myfile)) {
$dataline= fgets($myfile);
$listes = explode("\n",file_get_contents("text.txt"));
$poc = $listes[0];
if($ch == 2){
$gol = str_replace(' ', ' ', $dataline)."\n";
$fh = fopen("newtext.txt",'a');
fputs($fh, $gol);
fclose($fh);
chmod("newtext.txt", 0777);
}
$ch = 2;
}
unlink("text.txt");
copy("newtext.txt", "text.txt");
chmod("text.txt", 0777);
unlink("newtext.txt");
fclose($myfile);
echo $poc;
flush();
?>
The code is working only for the first two lines in text.txt but when it should read the third line the code stop working. Any advice please.
$handle = fopen("file", "r");
$first = fgets($handle,2048); #get first line.
$outfile="temp";
$o = fopen($outfile,"w");
while (!feof($handle)) {
$buffer = fgets($handle,2048);
fwrite($o,$buffer);
}
fclose($handle);
fclose($o);
rename($outfile,$file);
credits to ghostdog74 for this solution link
Related
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
i was wondering if it is posible to delete a single line in a txt file with php.
I am storing emailadresses in a flat txt file named databse-email.txt
I use this code for it:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email-subscribe'] . ',' . "\n";
$store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
if($store === false) {
die('There was an error writing to this file');
}
else {
echo "$email successfully added!";
}
}
?>
Form:
<form action="" method="POST">
<input name="email-subscribe" type="text" />
<input type="submit" name="submit" value="Subscribe">
</form>
The content of the file looks like this:
janny#live.nl,
francis#live.nl,
harry#hotmail.com,
olga#live.nl,
annelore#mail.ru,
igor#gmx.de,
natasha#hotmail.com,
janny.verlinden#gmail.com,
All lines are , seperated
Lets say i want to delete only the emailadres: igor#gmx.de
How can i do that?
What i want to achieve is a unsubscribe form and delete a single line in the .txt file
You can use str_replace
$content = file_get_contents('database-email.txt');
$content = str_replace('igor#gmx.de,', '', $content);
file_put_contents('database-email.txt', $content);
Because of the way the filesystem works you can't do this in an intuitive way. You have to overwrite the file with all the lines except the one you want to delete, here's an example:
$emailToRemove = "igor#gmx.de";
$contents = file('database-email.txt'); //Read all lines
$contents = array_filter($contents, function ($email) use ($emailToRemove) {
return trim($email, " \n\r,") != $emailToRemove;
}); // Filter out the matching email
file_put_contents('database-email.txt', implode("\n", $contents)); // Write back
Here's a streaming alternative solution in the cases where the file does not fit in memory:
$emailToRemove = "igor#gmx.de";
$fh = fopen('database-email.txt', "r"); //Current file
$fout = fopen('database-email.txt.new', "w"); //New temporary file
while (($line = fgets($fh)) !== null) {
if (trim($line," \n\r,") != $emailToRemove) {
fwrite($fout, $line, strlen($line)); //Write to new file if needed
}
}
fclose($fh);
fclose($fout);
unlink('database-email.txt'); //Delete old file
rename('database-email.txt.new', 'database-email.txt'); //New file is old file
There is also a way to do this in-place to minimize extra disk needed but that is trickier.
You can do it programmatically which will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file . Like below
$DELETE = "igor#gmx.de";
$data = file("database-email.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("database-email.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
first read the file using fopen and fget , and make array to list the emails you want to remove , use in_array to check if value exists in array , and then after remove unwanted emails save the file using fwrite and you need to close the file after the read and the write operations using fclose
checkout this code
$data = "";
$emailsToRemove = ["igor#gmx.de" , "janny#live.nl"];
//open to read
$f = fopen('databse-email.txt','r');
while ($line = fgets($f)) {
$emailWithComma = $line . ",";
//check if email marked to remove
if(in_array($emailWithComma , $emailsToRemove))
continue;
$data = $data . $line;
}
fclose($f);
//open to write
$f = fopen('databse-email.txt','w');
fwrite($f, $data);
fclose($fh);
for delete special word and next delete blank line try this:
$file = "file_name.txt";
$search_for = "example_for_remove";
$file_data = file_get_contents($file);
$pattern = "/$search_for/mi";
$file_data_after_remove_word = preg_replace($pattern, '', $file_data);
$file_data_after_remove_blank_line = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $file_data_after_remove_word);
file_put_contents($file,$file_data_after_remove_blank_line);
This question already has answers here:
PHP: Read Specific Line From File
(13 answers)
Closed 7 years ago.
I want read a line in file text. EX line 5. Any body can help me????
$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
echo fgets($fp);
}
fclose($fp);
Thanks for read
You can use the fgets() function to read the file line by line:
<?php
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line.'<br/>';
}
fclose($handle);
} else {
// error opening the file.
}
?>
$myFile = "text.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
PHP - Reads entire file into an array
Just put an incremental counter in your loop, only echo if that counter matches your requred line number, then you can simply break out of the loop
$required = 5;
$line = 1;
$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
if ($line == $required) {
echo fgets($fp);
break;
}
++$line;
}
fclose($fp);
This question already has answers here:
How to read a large file line by line?
(14 answers)
Closed 8 years ago.
I am developing a website in PHP, and I must include in the index the first 3 lines of a text file in PHP. How can I do that?
<?php
$file = file_get_contents("text.txt");
//echo the first 3 lines, but it's wrong
echo $file;
?>
Even more simple:
<?php
$file_data = array_slice(file('file.txt'), 0, 3);
print_r($file_data);
Open the file, read lines, close the file:
// Open the file for reading
$file = 'file.txt';
$fh = fopen($file, 'rb');
// Handle failure
if ($fh === false) {
die('Could not open file: '.$file);
}
// Loop 3 times
for ($i = 0; $i < 3; $i++) {
// Read a line
$line = fgets($fh);
// If a line was read then output it, otherwise
// show an error
if ($line !== false) {
echo $line;
} else {
die('An error occurred while reading from file: '.$file);
}
}
// Close the file handle; when you are done using a
// resource you should always close it immediately
if (fclose($fh) === false) {
die('Could not close file: '.$file);
}
The file() function returns the lines of a file as an array. Unless the file is huge (multiple megabytes), you can then use array_slice to get the first 3 elements of this:
$lines = file('file.txt');
$first3 = array_slice($lines, 0, 3);
echo implode('', $first3);
I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
currently I am able to remove a specific line from text file using php. However, after removing that line, there will be an empty line left behind.
Is there anyway for me to remove that empty line so that the lines behind can move up?
Thank you for your help.
$DELETE = "the_line_you_want_to_delete";
$data = file("./foo.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("./foo.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file.
Really? I find this muuuuch easier, only one line of code:
file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));
You can improve this by setting conditions to predict errors.
<?PHP
$file = "a.txt";
$line = 3-1;
$array = file($file);
unset($array[$line]);
$fp = fopen($file, 'w+');
foreach($array as $line)
fwrite($fp,$line);
fclose($fp);
?>