John Davidson

php export multiple csv files using a function

0 comments
Message:


I wrote a function in php to write data from database table to csv file:


  function export( $result,$filename)
{
header( 'Content-Type: application/csv' );
header('Content-Disposition: attachment; filename="'.$filename.'"');
$output = fopen("php://output", "w");
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
exit;
}

I had to put exit; or die at the end to prevent html code from being printed with the csv file , but the problem is when i call this function twice for two different files


export($result1,"file1.csv");
export($result2,"file2.csv");

it return one file only !


I think the exit is causing the problem ,but how can i resolve this ?


Update:


With or without the exit; statement the execution of php page simply stops at the first call of the function why it that ?


Regards



My Answer:
'.$filename.'.csv');_ $fp = fopen('php://output', 'w');_ while ($row = mysqli_fetch_assoc($result)) {_ fputcsv($fp, $row);_ }_ fclose($fp);_}_// Usage example_$result = mysqli_query($conn, "SELECT * FROM table_name");_export($result, 'exported_data');

Rate this post

3 of 5 based on 7425 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us