Is it possible to put the file_put_contents() function inside a while() loop?
I am trying to get my script to write lines into a text file - there's over 4 thousand lines to write.
$glassquery = $db->query("SELECT item FROM glass");
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL);
}
So it's writing the item name into the text file then the next one on a new line.
I think what you want is the FILE_APPEND flag:
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL, FILE_APPEND);
}
This will write the lines one at a time without erasing previous lines.
Related
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);
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.
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
I have a list.txt file which I get its contents with fgets. I then echo the contents of each line in the list.txt file in a while loop until fgets reaches end of file. Now, I want to delete a line after it has been echoed in the lists.txt file after it has been echoed.
I've tried putting the lines in another file (list2.txt) and then using the ideas of put_contents but i've been unsuccessful in doing that and in a few other things i've thought of to try. I can't help but feel like i'm overthinking it.
$list = fopen("list.txt","r");
while(! feof($list))
{
try{
$lines = fgets($list);
echo "$lines \n";
// I don't need to delete the lines here
}
catch (Exception $e)
{
echo "Error \n ";
// I want to delete the lines here
exit;
}
}
fclose($list);
// I want to delete the lines here
I was able to finally do this using file() and for loop but couldn't with fgets and while loop. Barmar's comment above pointed me in the right direction but implode wasn't cutting it for me.
$list = file('list.txt'); // opens list.txt into an array
$listcount = count($list); // counts the number of lines/array elements
for ($x = 0; $x <= $listcount; $x++) //for loop to echo and delete each line
{
echo "\n $list[$x]\n";
unset($list[$x]); // deletes the lines that's just being echoed
file_put_contents("list.txt", $list); // puts the remaining contents of
//the array back into list.txt file
}
Hellooo,
I wrote myself a little PHP experiment. This script counts how many times the user clicked a button labeled with a specific class (id="link_1", class="heart")
During each click, the script reads a txt file, finds the right id, then adds +1 to that id's number, like so:
#counte_me.php
$file = 'count_me.txt'; // stores the numbers for each id
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
fclose($fh);
file_put_contents($file, $lines, LOCK_EX);
The result
# count_me.txt
hello_darling||12
This works wonderfully well. The problem happens when, from time to time, I find myself staring at an empty count_me.txt!
Not really know when or how it happens, but it does. I start making increments and happens, sometimes sooner, sometimes way later. It may be on my way to 10 or to 200 or to 320 or anything in between. Its totally random.
Driving me crazy. I'm not experienced enough, but that's why I'm playing with this thing.
Someone knows what I am doing wrong here for the file to get dumped like that?
UPDATE 1
So far, Oluwafemi Sule's suggestion is working, but I have to remove LOCK_EX from the file_put_contents for it to work, otherwise it just doesn't.
// NEW LINE ADDED
if (!empty($lines)) {
file_put_contents($file, $lines);
}
$lines is initially set to an empty string and only updated on the following condition.
if(!empty($item)) {
# and so on and so on
}
And finally at the end,
file_put_contents($file, $lines, LOCK_EX);
The reason that $lines still remains set to the initial empty string happens when item is empty. Remember the newline added from "$item||$num\r\n", there could be more than a single line added there(I won't put it past a text editor to add a new line to end that file .)
I suggest to only write to the file when $lines isn't empty.
if (!empty($lines)) {
file_put_contents($file, $lines, LOCK_EX);
}
What is the best way for adding a line to a textfile? When I run the below code, it overwrites all lines.
Also when adding a line it contains some "s:4:" & s:60: characters. What does this mean? I just want to add the $photourl to urls.txt.
<?php
foreach ($_POST['photoselect'] as $photourl) {
file_put_contents($target_dir . '/urls.txt', $photourl);
$fp = fopen($target_dir . '/urls.txt','w');
fwrite($fp,serialize($photourl));
}
?>
You can append with file_put_contents
file_put_contents($target_dir . '/urls.txt', $photourl, FILE_APPEND);
When opening a file, the last parameter indicates how you want the file pointer to be set. With 'w', this truncates the file, you probably want to have 'a' which means put the pointer at the end of the file. ( see http://php.net/manual/en/function.fopen.php modes )
Unless you content contains special characters, just write it and not serialize it.
Your code also overwrites the file each time...
$fp = fopen($target_dir . '/urls.txt','a');
foreach ($_POST['photoselect'] as $photourl) {
fwrite($fp,$photourl.PHP_EOL);
}
fclose($fp);
My colleague and I are working on a chat application for a small Flash based game. We would like to keep our chat file as small as possible by automatically deleting old text after the file has reached a certain limit. Say the file exceeds 50 lines, we would like to delete the existing information and begin again at line 1. Is this possible?
<?php
$file = "saved.txt";
$edited_text = $_POST['new_text'];
$open = fopen($file, "a+");
fwrite($open, "\n" . $edited_text);
fclose($open);
?>
Basically something like this:
$lines = file('saved.txt');
$lines[] = 'new line of text';
array_unshift($lines); // remove first array element
file_put_contents('saved.txt', implode(PHP_EOL, $lines));
Read the file into an array, one line per array element
Append your new line(s) of text
Remove as many lines from the start of the array as necessary
dump array back out to file as text.
This would work:
// Read entire file
$lines = file_get_contents('saved.txt');
// Add what you want to the beginning of array
array_unshift($lines, 'new line of text');
// Keep first 50 items
$lines = array_splice($lines, 0, 50);
// Write them back
file_put_contents('saved.txt', implode(PHP_EOL, $lines));
Will always keep the first 50 elements intact (which includes messages from new to old).