How to add lines to a CSV file without overwriting it - php

$file = fopen("contacts.csv","w");
foreach(array_unique($matches[0]) as $email) {
fputcsv($file,explode(',',$email));
}
fclose($file);
The above code generates a CSV file. How can I update the CSV from the last recorded line without overwriting from the beginning?

Change "w" to "a" in the fopen. It changes "write" into "append".
"append" opens the file and writes at the end of the file, not from the beginning like "write".
i.e. change this line
$file = fopen("contacts.csv","w");
to
$file = fopen("contacts.csv","a");

Related

merge csv files using PHP

I have a .csv file which I can use with Google maps API to successfully create map data.
What I'm looking to do is merge 2 (or more) .csv files and display the TOTAL data on the Google map in the same way. They are all in the same format.
I have the paths to the 2 csv files and if need be, a blank .csv file in the same directory where the files could be merged to...
Unfortuantely, the .csv files all have an initial 'header row' which would be awesome to omit when merging...
If anyone can point me in the right direction, I'd be very happy. Thanks
edit: I've tried:
$data1 = file_get_contents('google_map_data.csv');
$data2 = file_get_contents('google_map_data2.csv');
$TOTALdata = "google_map_dataALL.csv";
function joinFiles(array $files, $result)
{
if(!is_array($files)) {
throw new Exception('`$files` must be an array');
}
$wH = fopen($result, "w+");
foreach($files as $file)
{
$fh = fopen($file, "r");
while(!feof($fh))
{
fwrite($wH, fgets($fh));
}
fclose($fh);
unset($fh);
fwrite($wH, "\n"); //usually last line doesn't have a newline
}
fclose($wH);
unset($wH);
joinFiles(array($data1, $data2), $TOTALdata);
I'm assuming both files are small, so loading them all in one go should be OK.
The code loads both files then removes the first line off the second one. It also removes any end of line from the first file, but adds it's own to ensure it always has a new line...
$data1 = file_get_contents('google_map_data.csv');
$data2 = file_get_contents('google_map_data2.csv');
$TOTALdata = "google_map_dataALL.csv";
$data2 = ltrim(strstr($data2, PHP_EOL));
file_put_contents($TOTALdata, rtrim($data1).PHP_EOL.$data2);

how can i add email in one by one using read/write in php

how can i add email in one by one using read/write in php
Am getting the following output and create one folder called "update" update folder contain user entered one email is stored and user enter another email id already existing email id replaced to new email id why?
I need one by one email id called
apap#gmail.com
asadsd#gmail.com
here are my code please review
<form action="demo.php" method="post">
<input type="text" name="textEmail">
<input type="submit" value="send">
</form>
Demo.php file are
<?php
// Open the text file
$f = fopen("update.txt", "w");
// Write text
$text = strtr(" ",' ', $_POST['textEmail']);
fwrite($f,$text);
//fwrite($f,$text);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("update.txt", "r");
// Read text
echo fgets($f);
fclose($f);
?>
Open the file in append mode instead of write mode
replace "w" with "a"
$f = fopen("update.txt", "a");
From: http://php.net/manual/en/function.fopen.php
'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...
Open your file as append mode so that you not need to open the file twice, for writing in the file, for you one email per line you need to use the \n after each email. For reading use the while loop to read end of the file and use fgets to make sure it reads the whole line at a time.
$myfile = fopen("update.txt", "a+");
$txt = $_POST['textEmail']."\n";
fwrite($myfile, $txt);
while(!feof($myfile)) {
echo fgets($myfile) . "<br/>";
}
fclose($myfile);
Documentation: php_file_create and php_file_open
I am unsure on what you are trying to achieve but I will clarify the difference between file write and file append.
Writing to a file when opened in 'w' mode writes from the current file pointer position which when open in 'w' mode is the very beginning of the file, to change this position in this mode use the fseek() method.
Writing to a file when opened in 'a' mode (append mode) will set the file pointer to the last location in the file and in php specifically will always when fwrite() is called will write to the end of the file.
Append File Example
Contents of update.txt before write:
sometext
sometext2
Code that writes to file
$f = fopen('update.txt', 'w');
//Description of 'a' mode from php manual
//Open for writing only; place the file pointer at the end of the file.
//If the file does not exist, attempt to create it. In this mode,
//fseek() has no effect, writes are always appended.
fwrite($f, "somevalue" . "\n");
fclose($f);
Results In an update.txt with contents:
sometext
sometext2
somevalue
Php doc on functions used in this example:
fopen()
fwrite()
<?php
if ($_POST['textEmail'] != '') {
$text = str_replace(" ", ' ', $_POST['textEmail']);
$pattern = '/([a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/';
preg_match_all($pattern,file_get_contents("update.txt"), $matches);
$emails = $matches[0]; // get Array of all email in file
if (!in_array($text, $emails)) { // echck for existing email
file_put_contents("update.txt", PHP_EOL.$_POST['textEmail'], FILE_APPEND);
}else{
echo 'Email address alerady exist';
}
echo $f = file_get_contents("update.txt");
}
?>
Would you please try this for demo.php ?

remove new line from txt file after insert value

i create a txt file from a folder in that way:
$fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp,$value."\n");
}
and it create inside the txt each items, one per line, BUT it also add a newline at the end of the file.
This is the content of mylist.txt:
foldelr/file1.mp3
folder/file2.mp3
(BLANK NEWLINE)
I tried to remove the blank newline at the end of the txt file, in this way:
$filetxt = fopen("mylist.txt","r");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("newfile.txt", $rtrim);
But it doesn't work, because in the "newfile.txt", i still have the newline blank after last file name.
I tried to convert file in array, use "array_diff()" to remove the last line, but it fail.
I tried also all the suggestions in this thread: remove new line characters from txt file using php but not fix my problem.
Does anyone can please help me to understand what i'm missing or mistaken?
Kind Regards
Brus
Use file_get_contents method it works fine for me
$fp = fopen("mylist.txt","rw+");
foreach (glob("test/*.*") as $value) {
fwrite($fp, $value . "\n");
}
$filetxt = file_get_contents("mylist.txt");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("mylist.txt", $rtrim);
Or You can also remove the last newline by using the array count.
$fp = fopen("mylist.txt","rw+");
$i =0;
foreach(glob("folder/*.*") as $value){
$i++;
if($i < count(glob("folder/*.*")))
fwrite($fp,$value."\n");
else
fwrite($fp,$value);
}
Have you tried to first write new line and only than value (assuming you already have content in file)?
fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp, "\n".$value);
}

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);

How to overwrite a particular line in flat file?

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.

Categories