我想将表导出到csv文件。该文件应保存到资产中的文件夹。在这里我使用强制下载。如何设置下载csv文件的路径?还有其他方法将表保存为csv文件到指定的文件夹。请帮帮我..
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM cyber_details";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
答案 0 :(得分:1)
试试这个,为我工作:
function createcsv(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM YourTable";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
答案 1 :(得分:0)
我假设您要在服务器端保存CSV文件。
您可以按照以下方式执行
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM cyber_details";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
if ( ! write_file('./path/to/file/file_name.csv', $data))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
确保您选择的路径具有足够的权限来执行写入操作。
答案 2 :(得分:0)
我也遇到了同样的问题。 下面的代码对我来说足够好。
$arry_to_csv[] = $data;
$output_file_name = 'path/to/Rejected.csv';
$temp_memory = fopen($output_file_name, 'w');
$csv_headers = array_keys($arry_to_csv[0]);
$delimiter = ",";
fputcsv($temp_memory, $csv_headers, $delimiter);
$csv = '';
foreach ($arry_to_csv as $line) {
$csv.= $line['first_name'] . ',' . $line['last_name'] . "\n";
}
fwrite($temp_memory, $csv);
fclose($temp_memory);