Search code examples
phpcsvfputcsv

fputcsv doesn't write any data in a CSV file


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.


Solution

  • It wasn't posting anything because it submit the page so that when the page refreshed all of my arrays are become empty.