I want to delete a line in txt file - php

I use PHP to read a txt file,I read the first line, it is ok.
but when I want to delete the first line.
it fails.....
I can do this code in localhost,but when I boot in server
it fail.....I dont know why...
this is my code:
<?php
$handle = fopen('newfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents = fgets($handle, 10);
echo $contents;
$filename = 'newfile.txt';
$content = file_get_contents('newfile.txt');
$content = str_replace($contents, '', $content);
file_put_contents('newfile.txt', $content);
exit;
}
fclose($handle);
}
?>

An alternative to the complicated code above ( which I did not check btw ) might be
$file='newfile.txt';
$lines=file( $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
array_shift( $lines );
file_put_contents( $file, implode( PHP_EOL, $lines ) );
If it is important to display the line that is being removed then:
$file='newfile.txt';
$lines=file( $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
$sentence = array_shift( $lines );
echo $sentence;
file_put_contents( $file, implode( PHP_EOL, $lines ) );

Related

Delete a specific line in a TXT file

I have a .txt file with millions of lines of text
The code below Delete a specific line (.com domains) in a .txt file. But large files can not do :(
<?php
$fname = "test.txt";
$lines = file($fname);
foreach($lines as $line) if(!strstr($line, ".com")) $out .= $line;
$f = fopen($fname, "w");
fwrite($f, $out);
fclose($f);
?>
I want to remove certain lines and put them in another file
For example, the list of domain names of sites. cut the .com domain and paste it in another file...
Here's an approach using http://php.net/manual/en/class.splfileobject.php and working with a temporary file.
$fileName = 'whatever.txt';
$linesToDelete = array( 3, 5 );
// Working File
$file = new SplFileObject( $fileName, 'a+' );
$file->flock( LOCK_EX );
// Temp File
$temp = new SplTempFileObject( 0 );
$temp->flock( LOCK_EX );
// Wite the temp file without the lines
foreach( $file as $key => $line )
{
if( in_array( $key + 1, $linesToDelete ) === false )
{
$temp->fwrite( $line );
}
}
// Write Back to the main file
$file->ftruncate(0);
foreach( $temp as $line )
{
$file->fwrite( $line );
}
$file->flock( LOCK_UN );
$temp->flock( LOCK_UN );
This may be slow though, but a 40 meg file with 140000 lines takes 2.3 seconds on my windows xampp setup. This could be sped up by writing to a temp file and doing a file move, but I didn't want to step on file permissions in your environment.
Edit: Solution using Rename/Move instead of second write
$fileName = __DIR__ . DIRECTORY_SEPARATOR . 'whatever.txt';
$linesToDelete = array( 3, 5 );
// Working File
$file = new SplFileObject( $fileName, 'a+' );
$file->flock( LOCK_EX );
// Temp File
$tempFileName = tempnam( sys_get_temp_dir(), rand() );
$temp = new SplFileObject( $tempFileName,'w+');
$temp->flock( LOCK_EX );
// Write the temp file without the lines
foreach( $file as $key => $line )
{
if( in_array( $key + 1, $linesToDelete ) === false )
{
$temp->fwrite( $line );
}
}
// File Rename
$file->flock( LOCK_UN );
$temp->flock( LOCK_UN );
unset( $file, $temp ); // Kill the SPL objects relasing further locks
unlink( $fileName );
rename( $tempFileName, $fileName );
It could be because of the large size of the file that its taking too much of space.
When you do file('test.txt'), it reads the entire file into an array.
Instead, you can try using Generators.
GeneratorsExample.php
<?php
class GeneratorsExample {
function file_lines($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
}
function copyFile($srcFile, $destFile) {
foreach ($this->file_lines($srcFile) as $line) {
if(!strstr($line, ".com")) {
$f = fopen($destFile, "a");
fwrite($f, $line);
fclose($f);
}
}
}
}
callingFile.php
<?php
include('GeneratorsExample.php');
$ob = new GeneratorsExample();
$ob->copyFile('file1.txt', 'file2.txt')
While you could use tens of lines of PHP code, one line of shell code will do.
$ grep Bar.com stuff.txt > stuff2.txt
or as PHP
system ("grep Bar.com stuff.txt > stuff2.txt");

search, insert & write on a new line of text file using PHP

i have problems in searching a string in a file, insert a new line after the searched string and write on the new added line. currently i am using below code from examples and discussion i found:-
$target = '<18>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$string_i_am_looking_for] = $put;
file_put_contents( $filename , implode( "\n", $lines ) );
text file:-
<17>
<18>
<19>
<20>
at first action, i was able to put the $put in the text file.
<17>
<18>Enter
<19>
<20>
but, when i change the $target = "<20>", i was not able to write after the new $target. It will appear next to the first line. And when i reload the page more and more, it will keep on writing on the first line. Below is the result:-
<17>EnterEnterEnterEnterEnter
<18>Enter
<19>
<20>
Word Enter is not new line in any manner. You have to replace it with \r\n or \n (depends on file new line character).
$target = '<18>';
$put = "\r\n";
$file = 'line.txt';
Try This
$target = '<20>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$key = array_search($string_i_am_looking_for,$lines);
$toSearch = $target.$put;
if(!in_array($toSearch,$lines)) {
$lines[$key] = $target.$put;
}
file_put_contents( $filename , implode( "\n", $lines) );

in php how to delete text line in txt / notepad file when txt reaches 100 lines

How to delete / clear lines of data if it reaches 100th line. I checked some examples, but it is not working.
I need to check the number of the line end if it reaches line number 100, delete or clear all in that text file.
The following code is taken from an example, but this is also not working:
<?php
$text = "log.txt";
$lines = explode("\n", $text);
$lines = array_slice($lines, 0, 10); //10 is how many lines you want to keep
$text = implode("\n", $lines);
?>
Something like this: you will need to take it and fit it to your application, but I think this is what you are looking for.
//Count lines
$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
//Remove lines
if ($linecount ==100)
{
$lines = file($file, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);
}

How to insert string before last line?

I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4
example line1
example line2
//i need insert here
lastline $eg};
My code is working but this is adding empty lines after all lines :
$filename = 'example.php';
$arr = file($filename);
if ($arr === false) {
die('Error' . $filename);
}
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here
$person = "my text here\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here
$file = "tmp/saf.txt";
$fc = fopen($file, "r");
while (!feof($fc)) {
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose($fc);
//open same file and use "w" to clear file
$f = fopen($file, "w") or die("couldn't open $file");
$lineCount = count($lines);
//loop through array writing the lines until the secondlast
for ($i = 0; $i < $lineCount- 1; $i++) {
fwrite($f, $lines[$i]);
}
fwrite($f, 'Your insert string here'.PHP_EOL);
//write the last line
fwrite($f, $lines[$lineCount-1]);
fclose($f);

read and write file with newline php

I have a php file with the following info
One
Two
Three
Now i want to split them into an array, so i used:
$filehandle = fopen($filename, 'rb');
$line_of_text = fgets($filehandle);
$array = explode("\n", $line_of_text);
But it is not working.
They are written in the file like this:
$filehandle = fopen($textfile, 'a');
fputs($filehandle, $line . "\r\n");
fclose($filehandle);
So how do i read them into an array?.
Thanks.
I think you are looking for file(). However, it should be noted that this will leave all your array elements with a trailing CRLF sequence on them.
Alternatively (all these will strip the trailing CRLF):
$array = explode("\r\n", file_get_contents($filename));
...or...
$fp = fopen($filename, 'r');
$filecontents = fread($fp, filesize($filename));
$array = explode("\r\n", $filecontents);
...or...
$fp = fopen($filename, 'r');
$array = array();
while (($line = fgets($fp)) !== FALSE) $array[] = trim($line);
You should use the file function
file — Reads entire file into an array
$your_array = file ("filename", FILE_IGNORE_NEW_LINES); // add the flag to strip newlines

Categories