我们需要在Code igniter中导出(下载)CSV文件。这将仅导出我的表数据,如何更改我的csv文件的格式?请任何人帮助我。
答案 0 :(得分:6)
Codeigniter有一个内置的类。试试这个:
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("Your SQL Here");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
答案 1 :(得分:1)
您可以在此处查看如何将数据库结果导出为CSV文件
http://www.code2learn.com/2012/03/generating-csv-file-using-codeigniter.html
或者您可以使用此代码
创建帮助器if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('array_to_csv'))
{
function array_to_csv($array, $download = "")
{
if ($download != "")
{
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $download . '"');
}
ob_start();
$f = fopen($download, 'wb') 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
{
echo $str;
}
}
}
if ( ! function_exists('query_to_csv'))
{
function query_to_csv($query, $headers = TRUE, $download = "")
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('invalid query');
}
$array = array();
if ($headers)
{
$line = array();
foreach ($query->list_fields() as $name)
{
$line[] = $name;
}
$array[] = $line;
}
foreach ($query->result_array() as $row)
{
$line = array();
foreach ($row as $item)
{
$line[] = $item;
}
$array[] = $line;
}
echo array_to_csv($array, $download);
}
}
/* End of file csv_helper.php */
/* Location: ./system/helpers/csv_helper.php */
然后你的控制器功能看起来像这样
function create_csv(){
$this->load->helper('url');
$this->load->helper('csv');
$query = $this->db->query('SELECT * FROM <tablename>');
$num = $query->num_fields();
$var =array();
$i=1;
$fname="";
while($i <= $num){
$test = $i;
$value = $this->input->post($test);
if($value != ''){
$fname= $fname." ".$value;
array_push($var, $value);
}
$i++;
}
$fname = trim($fname);
$fname=str_replace(' ', ',', $fname);
$this->db->select($fname);
$quer = $this->db->get('<tablename>');
query_to_csv($quer,TRUE,'Products_'.date('dMy').'.csv');
}
}