How to overwrite a text using fopen
$data = 'HHHHHHHHHHHHHHH';
$data2 = 'JJJJJJJJJJJJJJ';
$F = fopen('tbbbb.txt','w');
fwrite($F,$data);
fwrite($F,$data2);
fclose($F);
I want output should be
"JJJJJJJJJJJJJJ"
in the file
You can use the fseek() function:
fwrite($F,$data);
fseek($F, 0);
fwrite($F,$data2);
Use rewind to return to the beginning of the file.
fwrite($F,$data);
rewind($F);
fwrite($F,$data2);
The resulting file contents will be:
JJJJJJJJJJJJJJH
because overwriting the beginning of the file doesn't replace what comes after it. You can call:
ftruncate($F, count($data2));
to set the file length.
fwrite will always write where the cursor position is and navigate the cursor to next line. So when you write first string, it will write to first line and navigate the cursor to next line. SO current cursor position is on second line. So if you want to overwrite a particular line you will have to seek to that line.
fseek($F, <byte_position>);
fwrite($F, <string>);
Use file_put_contents()
file_put_contents('file.txt', $data);
echo file_get_contents('file.txt'); // HHHHHHHHHHHHHHH
file_put_contents('file.txt', $data2);
echo file_get_contents('file.txt'); // JJJJJJJJJJJJJJ
Related
For storing values in a .txt file I use this code:
file_put_contents('data/vote_result.txt', implode(',', $results));
and for reading i use this:
$results = explode(',', file_get_contents('data/vote_result.txt'));
The content of vote_result.txt looks like this: 0,1,2,3
How can I store a second line in the same .txt file so that the content looks like this:
0,1,2,3
0,1,2,3
and how can I read that second line?
Read second line:
$myFile = "data/vote_result.txt";
$linesArray = file($myFile);
echo $linesArray[1]; //line 2
If you want to append a line to file, use FILE_APPEND flag in file_put_contents and concatenate "\n" with implode.
file_put_contents('data/vote_result.txt', implode(',', $results)."\n", FILE_APPEND);
Besides that you should use a database like MySQL for this, you can use the file function. Example:
$data = file('file.txt');
print $data[1]; // printing out the second line
This given you can simply add new lines just by adding a new entry in the array and then implode it with the newline character and save it via the file_put_contents function.
$content = implode("\n", $data);
file_put_contents('file.txt', $content);
I have to insert text to a file at a specific position without reading/writing the entire file. Is that possible using just php?
mytext.txt content is 123456789
<?php
$message='new';
$file='mytext.txt';
$fh = fopen($file, 'rw+');
fseek($fh, 3);
fwrite($fh, $message);
fclose($fh);
?>
This code overwrites at the specified location.
I'm looking for '0123new456789' not '123new789'
I don't think what you want to do is possible without reading the file first. This should help, though:
// Get file contents
$contents = file_get_contents($file);
// Split your strings
$beginning = substr($contents, 0, 4);
$ending = substr($contents, 4, 6);
// Re-write contents
$contents = $beginning . $message . $end;
// Write file contents
file_put_contents($file, $contents);
Thanks,
Andrew
You have no choice.
fopen() allways put the pointer at the beginning or end of file. In any case you must to pass trough the file untill you find what you are looking for. There you can close.
See the document about it http://php.net/manual/en/function.fopen.php
By the way, fseek($fh, 3) is not mean to find 3. Is is retrieve something in the 3 bytes length. See http://php.net/manual/en/function.fseek.php
1st line
2nd line
...
//append here
last line
I have a php script use file put content append
I need to append between last 2nd line & last line?
anyone know how to achieve this?
Alternatively, you could use file(), and outputs an array. From there you can determine the second to the last line. Consider this example:
$replacement = "Hello World";
$contents = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$size = count($contents);
$contents[$size-2] = $replacement; // point it to the second last line and assign
$temp = implode("\n", $contents);
file_put_contents('file.txt', $temp);
I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).
I have a text file that has information like this
##john##eva##shawn##roger##henry##david
I want to get the very last name at the end and ingnore rest.
How'd I do that
THanks
Big file solution:
$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");
$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
$seek_position = $seek_position - 1024;
if(abs($seek_position) > $file_size)
break;
fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
Small file solution:
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);
Use fseek to quickly jump to the end of the file.
$handle = fopen("myfile.txt", "r");
fseek($handle, -20, SEEK_END);
$bytes = fread($handle, 20);
Will read the last 20 bytes of the file (and skip the rest).
Unless you know how long the last name is going to be or at least the max length of names you can't really skip just to end of a file and pull out the name.
What you need to do is read the file into a buffer and parse it either using something like explode() and '##' and getting the last element of the returned array or using strpos() to find the last occureance of '##'and reading on from there.
Here is an example with explode.
$sFileName = "file.txt";
$sContents = file_get_contents($sFileName);
$aNames = explode("##", $sContents);
$sLastName = $aNames[count($aNames)-1];
After loading the file into a variable, you can find the last ocurrence of "##" using strpos() and then read from there on using substr().
You can explode the whole string to an array and then use the php's end() function, like this:
// define our string
$string = "##john##eva##shawn##roger##henry##david";
// use the explode function to create an array using the delimiter ##
$array = explode("##", "##john##eva##shawn##roger##henry##david");
// print last object of the array using the php's end function
print end($array);