I would like to generate a csv file with data, that I get by querying a database. The browser then should prompt the user to download the file. By problem is, that the readfile function needs a filename and not a handle, but I can't find a function to get the filename of this temporary file.
I guess there are better ways to do this, but I can't find them.
$handle = tmpfile();
fputcsv($handle, array('year', 'month', 'product', 'count'));
header('Content-Type: application/csv');
header('Content-Disposition:attachment;filename=LS_export');
echo readfile($handle);
fclose($handle);
exit();
You are looking for rewind to reset the file pointer to the start of the file, followed by fpassthru to output all the contents of the file.
rewind($handle);
fpassthru($handle);
Another solution is to use tempnam to generate a unique file which is not removed when closed. Do not forget to remove it manually when you are done with it.
$name = tempnam('/tmp', 'csv');
$handle = fopen($name, 'w');
...
fclose($handle);
readfile($name);
unlink($name);
Use
$tmpfname = tempnam("/", "");
$handle = fopen($tmpfname, "w");
...
fclose($handle);
And you have the filename too.
from mysql
SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE 1
and delete it on demand
redefine separators and other param as you need
Related
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);
I have created a form and able to add data to CSV on submit. But my code is such that the csv file is delimited by commas and so when I add comma in the form data, the php code separates it as another entry (column).
Here is my php code:
<?php
$filename = "data.csv";
$string = $_POST['element_1'].",".$_POST['element_2'].",".$_POST['element_3'].",".$_POST['element_4_1']."-".$_POST['element_4_2']."-".$_POST['element_4_3'].",".$_POST['element_5']."\n";
if (file_exists($filename)) {
$file = fopen($filename, "a");
fwrite($file, $string);
} else {
$file = fopen($filename, "a");
fwrite($file, '"Name","Phone","No. of persons","Date","Venue"\n');
fwrite($file, $string);
}
fclose($file);
?>
In the above code, Venue sometimes, takes 'commas'. But the code separates the Venue data into new columns.
So, is there any other way to enter data into excel sheet other that CSV or any code gimmick.
You can make your life easier by using fputcsv and fgetcsv.
fputcsv lets you specify the delimiter and enclosure you need. The big difference is that you must pass the fields as an array: each value of the array is a column value in the csv line.
So given a $fields array that contains your CSV line values:
$file = fopen( 'data.csv', 'a' );
fputcsv( $file, $fields, ',', '"' );
fclose( $file );
Important: the flag on fopen must be a in order to append to the file. If you use w you will overwrite the previous content.
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.
This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
Hi I want to append a row at the beginning of the file using php.
Lets say for example the file is containing the following contnet:
Hello Stack Overflow, you are really helping me a lot.
And now i Want to add a row on top of the repvious one like this:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
This is the code that I am having at the moment in a script.
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
Need to write at beginning of file with PHP
which says the following to append at the beginning:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
And other one here:
Using php, how to insert text without overwriting to the beginning of a text file
says the following:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?
Looking for your thoughts on this!!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "\n" . $fileContent);
}
usage :
file_prepend("couldn't connect to the database", 'database.logs');
My personal preference when writing to a file is to use file_put_contents
From the manual:
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
Because the function automatically handles those three functions for me I do not have to remember to close the resource after I'm done with it.
There is no really efficient way to write before the first line in a file. Both solutions mentioned in your questions create a new file from copying everything from the old one then write new data (and there is no much difference between the two methods).
If you are really after efficiency, ie avoiding the whole copy of the existing file, and you need to have the last inserted line being the first in the file, it all depends how you plan on using the file after it is created.
three files
Per you comment, you could create three files header, content and footer and output each of them in sequence ; that would avoid the copy even if header is created after content.
work reverse in one file
This method puts the file in memory (array).
Since you know you create the content before the header, always write lines in reverse order, footer, content, then header:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
then you call write_reverse() first with footer, then content and finally header. Each time you want to add something at the beginning of the file, just write at the end...
Then to read the file for output
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
Then there is another consideration: could you avoid using files at all - eg via PHP APC
You mean prepending. I suggest you read the line and replace it with next line without losing data.
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>
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.