Fputcsv does not write any data to the CSV file

On my website, I create a table from mysql data, and then now I want to add the buttom export button of the table so that the user can load the data as a CSV file.

For this, I wrote a 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 mysql stuff, I create an array and insert 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 clicking the export button, I will have the exportme2.csv file, but it is empty! The data may be incorrect, so there will be nothing but, at a minimum, I should have the names of the headers.

Can you help me in this matter?

Thanks.

+1
source share
3 answers

He did not publish anything because he sent the page so that when I refresh the page, all my arrays become empty.

0
source

First of all, change

 $fp = fopen('exportme2.csv', 'w'); 

to

 $fp = fopen('exportme2.csv', 'a'); 

how 'w' truncates the file, where 'a' creates or adds the file.

Then you should use flock() to make sure that two different users (streams) are not trying 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 this is not fixed, then you have a typo in your code somewhere that is not obvious to me.

+1
source

This works well 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 fclose, so it was listening to your file ... you have to develop with E_ALL E_STRICT enabled!

+1
source

Source: https://habr.com/ru/post/1239208/


All Articles