I have been trying to make a WordPress page that will export .csv file with the data from my table “statistics”. This script below is working perfectly on localhost if I put it in .php file.
But in WordPress, it does not work my way. I have put this script in a separate page using plugin for insert php. It downloads .csv file when I access this page, but the data inside is not the data from table. It gives data, with div tags and errors. I tried also other script from Exchange, and again, it returns this strange file, so obviously the problem is in WordPress and my understanding of the same.
CODE: I put this script on www.mydomain.com/export (this is wordpress page).
[insert_php]
global $wpdb;
$result = $wpdb->get_results('SELECT * FROM statistics', ARRAY_A);
header('Content-Type: text/csv');
$date = date("Y-m-d H:i:s");
header('Content-Disposition: attachment;filename=EXPORT_' . $date . '.csv');
foreach ($result as $row) {
if ($row) {
exportCsv(array_keys($row));
}}
while ($row) {
foreach ($result as $row) {
exportCsv($row);
}}
function exportCsv($rows) {
$separator = '';
foreach ($rows as $row) {
echo $separator . $row;
$separator = ',';
}
echo "rn";
}
[/insert_php]
What am I missing? How to make this happens? I want to make an export of one table in MySQL that will export it nicely formatted in .csv file, so users can download it on computer.
Export database table to csv using WordPress page and php.
I seriously doubt that code could work: that
while ($row)
is always true (infinite loop).I changed a little:
Maybe this code can do what you want?
https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv