I am trying to export a list page to csv file using the code below.
public function export()
{
$customers = \CI::Customers()->get_customer_export();
\CI::load()->helper('download_helper');
force_download('customers.csv', ($customers));
}
It generates and error that second parameter should be a string not any array.Also if i try to json_encode the $customers variable,it creates a file but outputs json code in the csv file.
Any help is appreciated
Try to use this function: first of all you have put this code in helper:
function array_to_csv($array, $download = "")
{
if ($download != "")
{
header('Content-Description: File Transfer');
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachement; filename="' . $download . '"');
header('Content-Transfer-Encoding: binary');
}
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$n = 0;
foreach ($array as $line)
{
$n++;
if ( ! fputcsv($f, $line))
{
show_error("Can't write line $n: $line");
}
}
fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
if ($download == "")
{
return $str;
}
else
{
print "\xEF\xBB\xBF"; // UTF-8 BOM
print $str;
}
}
Array formation should be like:
Array
(
[0] => Array
(
[0] => 1
[1] => 0
[2] => Test 1
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => Test 1.1
)
[2] => Array
(
[0] => 3
[1] => 1
[2] => Test 1.2
)
)
You may also use a 'CI database utility class' for simplicity as follows:
$this->load->dbutil();
$query = $this->db->query("SELECT * FROM mytable");
echo $this->dbutil->csv_from_result($query);
Check the user guide below for more information https://www.codeigniter.com/userguide3/database/utilities.html