fputcsv doesn't write any data in a CSV file

坚强是说给别人听的谎言 提交于 2020-01-04 06:38:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!