Reputation: 11
I have php code that open an txt file then click click enter 2 times, then write data sample
1
2
3
i just want help to write same data but in first line in txt file mean php open the txt then go to first line and before the texts, and click enter two times then enter the same data, sample will be
3
2
1
this is my code
<?php
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$nice=$_POST['namee'];
$date = date('m/d/Y h:i:s a', time());
date_default_timezone_set('Etc/GMT-3');
$fp = fopen('data.txt', 'a');
~ here I want code to select first line in txt file
fwrite($fp, "\n" );
fwrite($fp, "\n" );
fwrite($fp,date('Y-m-d') . ' - ' . date('H:i:s'). "\n");
fwrite($fp, $nice);
Upvotes: 1
Views: 61
Reputation: 12045
If I understand correctly, you want to prepend something to the file... does it have to be with fopen()
?
In my opinion easier and much more understandable solution, but uses more memory, as it loads the whole file, so not usable on huge files:
<?php
$toPrepend = "\n\n";
$myFile = 'data.txt';
file_put_contents($myFile, $toPrepend . file_get_contents($myFile));
You can also load whole file into an array (every item of array will be one line) with:
<?php
$file_lines = file($myFile);
And then change any line you want, like
<?php
$file_lines[0] = 'add this before the first line' . $file_lines[0];
$file_lines[1] = 'add this before the second line' . $file_lines[1];
$file_lines[2] = trim($file_lines[2]) . 'add this after the third line' . "\n"
// last one is more complicated, as every line ends with EOL character(s);
And save it:
<?php
file_put_contents($myFile,implode("",$file)); // you need to implode array to string
Upvotes: 0
Reputation: 972
As mentioned in the comments, opening the file with fopen('data.txt', 'r+')
will set the file pointer to the beginning of the file.
Also, once you have already written something, it's possible to set the file pointer to a new location (e.g. beginning of the file):
fseek($fp, 0)
- this sets the file pointer to the beginning of the file.
You can also use: rewind($fp)
, which does the same thing.
Upvotes: 1