问题
In my web site I'm creating a table from the mysql data and then now I want to add a export button buttom of the table so that a user will be able to download the data as an CSV file.
To do that I wrote dummy form:
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="submit" value="Click Me">
</form>
And at the top of the php file I have:
if(isset($_POST['submit'])) {
export();
}
In my export function I have some mysql stuff, I'm creating an array and pushing data into it, and then:
$header = array('name', 'date', 'total', 'success', 'opens', 'clicks', 'success_rate', 'open_rate', 'CTO', 'CTR')
$fp = fopen('exportme2.csv', 'w');
fputcsv($fp, $header);
foreach ($data as $lines) {
fputcsv($fp, $lines);
}
fclose($fp);
After I click to export button, I'll have exportme2.csv file, however it is empty ! The data may be wrong so that there won't be anything but at least I should have the header names.
Can you help me about this issue please ?
Thanks.
回答1:
First off, change
$fp = fopen('exportme2.csv', 'w');
to
$fp = fopen('exportme2.csv', 'a');
as 'w'
truncates the file, where 'a'
creates or appends the file.
Then you should use flock()
to make sure two different users (threads) don't try to write to the file at the same time:
if (!flock($fp, LOCK_EX)) {
error_log('Cannot get lock!');
} else {
fputcsv($fp, $header);
foreach ($data as $lines) {
fputcsv($fp, $lines);
}
}
If that doesn't fix things, then you have a typo in your code somewhere that isn't obvious to me.
回答2:
This is running good for me :
$header = array('name', 'date', 'total', 'success', 'opens', 'clicks', 'success_rate', 'open_rate', 'CTO', 'CTR');
$fp = fopen('exportme2.csv', 'w');
fputcsv($fp, $header);
/*foreach ($data as $lines) {
fputcsv($fp, $lines);
}*/
fclose($fp);
Your above script stopped before the fclose, so it bugged your file ... You should develop with the E_ALL E_STRICT enabled !
回答3:
It wasn't posting anything because it submit the page so that when the page refreshed all of my arrays are become empty.
来源:https://stackoverflow.com/questions/11549414/fputcsv-doesnt-write-any-data-in-a-csv-file