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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With