Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query mysql and export data as CSV in PHP

Tags:

php

mysql

csv

I have myssql db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from PHP MYSQLi Displaying all tables in a database

But how do I export this information as a csv file? I have tried instead of echo changed it to a string and print the string to a csv file but it is not working.

I have also tried the example from: http://sudobash.net/php-export-mysql-query-to-csv-file/

But I can see the data but on top there is also junk (like "<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>"
etc) inside the csv file.

Is there another way to do this?

like image 645
aandroidtest Avatar asked May 06 '13 03:05

aandroidtest


1 Answers

If you want to write each MySQL row to a CSV file, you could use the built in PHP5 function fputcsv

$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

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

foreach ($row as $val) {
    fputcsv($fp, $val);
}

fclose($fp);

Which should return a comma separated string for each row written to file.csv:

row1 val1, row1 val2
row2 val1, row2 val2 
etc..

Also be sure to check permissions for the directory you are writing to.

like image 154
dcd0181 Avatar answered Oct 06 '22 11:10

dcd0181