How to overwrite a particular line in flat file? - php

My text file contains:
a
b
c
d
e
I can't figure out how to amend my code so that I can overwrite line 3 ONLY (ie replacing "c") with whatever I type into the input box 'data'. My code is as follows, currently the contents of the input box 'data' replaces my file entirely:
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "w") or die("Couldn't open $file for writing");
fwrite($fp, $data) or die("Couldn't write values to file");
fclose($fp);
I have it working the other way around, ie the code below reads line 3 ONLY into the text box when the page first loads:
$file = "data.txt";
$lines = file( $file );
echo stripslashes($lines[2]);
Can anybody advise the code I need to use to achieve this?

The only way is to read the whole file, change the 3rd line, then write it all back out. Basically, like so:
$lines = file($file);
$lines[2] = $_POST['data'];
file_put_contents($file, implode("\n", $lines));
Btw, your reading code does not "ONLY" read line 3 - it reads all lines as per file() and then you only use line 3.

Related

Loop through text file, amend & write new file PHP

I have a file called test.txt. It has multiple lines of text in it like thus:
Test Data:
Tester 2 Data:
Tests 3 Data:
I would like to have a PHP script that opens this file, strips ALL of the text before the word Data: on each row and outputs the result:
Data:
Data:
Data:
My PHP so far:
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
$data = fread($myfile,filesize("test.txt"));
// foreach line do this
$line = strstr($data,"Data:");
//append $line to newtest.txt
// endforeach
fclose($myfile);
You can use file() to open and loop over a file line by line.
As you are removing everything before Data:, based on your test data supplied (which is all I have to go on), we only need to know the number of lines. So, we can use count() to get that information.
Then construct the new data as a variable, and finally write that variable to a (new) file using file_put_contents().
Using trim() will remove the last extra line return.
$raw = file("./test.txt");
$lineCount = count($raw);
$newFile = null;
do {
$newFile .= "Data:\r\n";
} while(--$lineCount > 0);
file_put_contents('./test-new.txt',trim($newFile));
Edit:
As Don't Panic says in the comment below, you could use str_repeat() to even remove the do while loop.
Here is that version with the count() moved in-line as well:
$raw = file("./test.txt");
$newFile = str_repeat("Data:\r\n",count($raw));
file_put_contents('./test-new.txt',trim($newFile));

read the first line of the txt file then delete that line with php

I have a huge txt file that have 475254 lines and with php I want to read the first line of the my txt file and save it into the Variable and then when I save it the php delete that line.
my txt file is about 2.3 MB is it possible to do this?
yes it is /.................................
OK less trolling..
You want fopen and fgets will grab a line. REF : fgets Manual PHP
$file = "file.txt"
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f); // You close because you only want the first one.
There are so many examples how to do this i feel embarrassed answering. You should show some of what you have tried first!
Now you want to remove it: use file_get_contents REF : PHP file_get_contents
//Get your file contents
$newDoc = file_get_contents($file, true);
$newFileContents = substr( $line, strpos($newDoc, "\n")+1 );
//then you want to save it
file_put_contents($newFileContents, $file);
I might be wrong but you get the idea!~ ;)
Process :
Get Contents of file
Get First Line
Replace content of all file with your First Line as New Line
Save File
Im sure there is a more efficient way to do this, im just winging!
NOTE: You may need to configure your php.ini to work with larger files!
yes, Mark is probably too lazy to even try bulid a code, but i have already a working code so.. copypasta
$file = "mydata.txt";
$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);
//do smth
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
//sleep(1);

php cannot write new line, file gets overwirtten

I have read a lot of questions, none of which worked. I have a txt file. The first line contains headers separated by a tab "\n". Now when i post to this file I want it to take the values and separate them by a tab and then write them on a new line of the txt file. But when I run it, it just overwrites the first line.
<?php
$post = $_POST;
$myFile = 'test.txt';
$fh = fopen($myFile, 'w');
$columns = "";
foreach ($post as $key => $value){
$columns .= $value . "\t";
}
fwrite($fh, $columns . PHP_EOL);
fclose($fh);
?>
You're looking for a instead w:
$fh = fopen($myFile, 'a');
From the docs:
'w' Open for writing only; place the file pointer at the beginning of
the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the
file. If the file does not exist, attempt to create it.
w is used for writing which means anything before gets overwritten.
Change the following line:
$fh = fopen($myFile, 'w'); //w = write
To
$fh = fopen($myFile, 'a'); //a = append
It should fix the issue for you.
Try $fh = fopen($myFile, 'a'); if you don't want to overwrite content.
Using w overwrites, while a or a+ appends.
For more information on the fwrite() function, you can consult the PHP manual.
http://php.net/manual/en/function.fwrite.php
Also consult the PHP manual on fopen() http://php.net/manual/en/function.fopen.php
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Explode() is giving server error, page can't load

<?php
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
print_r ($theData);
fclose($fh)
?>
This is my current code, which has successfully read my file and printed the data to the screen. However now when I try to explode the data I just get a sever error and the page doesn't load at all, the only error message I get is page may be down for maintenance or configured incorrectly and I don't understand why it isn't working.
I am trying to put
$my_array = explode("/n", $theData);
after the data has been read, and before it is printed, but every time I add it the page gives up, but when I take it out the page loads again fine.
I need to be able to put in a foreach loop to explode the data and print it out one line at a time (it's an email directory) but I don't understand why it's not working.
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array()
$my_array = explode("\n", $theData);
foreach($my_array as $line)
{
$tmp = explode(" ", $line);
$assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh)
$mail = $assoc_array;
I have tried this code, which I found while doing the original research for how to read from .txt file to array, but it still throws up the server error problem.
Could someone explain where I'm going wrong?
In the end the code I've used is:
<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
print_r ($array);
?>
I've managed to read the data and print each line out into an array, now all I need to do is make it look nice! Thanks a lot for your help guys!
Initial problems
Looks like you have a few missing semicolons, unless you typed the reference code by hand and your actual code is correct.
$assoc_array = array()
fclose($fh)
offset 1 does not exist
$tmp[1] does not exist, which means some $tmp either had no values or only one value. It is most likely the case that one of the lines is a single word without a space or completely empty.

Writing some data to a specific area within a file in PHP

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?
Ideally, I'd like to:
Use fopen to get the file
Search for a comment called <!-- test -->
Replace that comment with new data.
This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).
Thanks!
<?php
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
}
?>
From: http://www.php.net/manual/en/function.fopen.php#81325
EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
?>
If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

Categories