Currently I am using following code to export mysql data to csv file
<?php
include("db.php");
$query = "SELECT * FROM my_table";
$delimiter = ",";
$filename = "MY-LIST-" . date('d-F-Y-H-i-s') . ".csv";
$f = fopen('php://memory', 'w');
$fields = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
fputcsv($f, $fields, $delimiter);
$result = $database->get_results($query);
foreach($result as $row){
$lineData = array($row['id'], $row['first_name'], $row['last_name'], $row['email'], $row['gender'],$row['country'], $row['date_created'], $row['member_status']);
fputcsv($f, $lineData, $delimiter);
}
fseek($f, 0);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
?>
Above Code is working ok ! and creating csv as expected.
Now I have another mysql table with around 89 columns and I want to export it to csv.
To reduce time consuming typing work, I need to fetch column names and put their values in array.
Current code I am trying is as follows :
<?php
include("db.php");
$result1 = $database->list_fields_name_serially('my_table');
// Getting all column names as comma separated list as id, first_name, last_name, email, gender, country, date_created, member_status, column_1, column_2, ......, column_89... (there is space after comma and before each column name)
$result2 = strtoupper(str_replace("_", " ", $result1)); // removing underscore
$result = strtoupper(str_replace(",", "' , ' ", $result2)); // replacing comaa with comma nad single quotes
$delimiter = ",";
$filename = "MY-LIST-" . date('d-F-Y-H-i-s') . ".csv";
$f = fopen('php://memory', 'w');
$fields = array($result); // output = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
fputcsv($f, $fields, $delimiter);
$field_name = explode(",", str_replace(" ", "", $result1));
$resultdata = $database->get_results("select * from my_table");
foreach($resultdata as $row){
foreach($field_name as $k => $v){
$lineData[$k] = array($row[$v]);
}
fputcsv($f, $lineData, $delimiter);
}
fseek($f, 0);
// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
?>
BUT IT IS NOT WORKING….. SCRIPT RUNS FOR FEW MINUTES AND THEN CREATES A CSV WITH ERRORS IN IT – Warnig : Array to string conversion on line 54 i.e. fputcsv($f, $lineData, $delimiter);