[英]csv export data with utf-8 encoding is garbled php
因此,我有此页面将数据库转换为csv。
转换设置为utf8时,数据库也设置为utf8。
问题是在excel中打开csv文件后,数据出现乱码。 看起来像这样:
KN01001 | 荳陦帙,admin@listmaster.com" | List Master | |
KN01002 | 譌ュ譚セ | information@e877.jp | Info Master |
但是当我尝试将文件拖到记事本中时,数据还可以,它显示:
"KN01001","荳陦帙","admin@listmaster.com","List Master"
"KN01002","譌ュ譚セ蝣","information@e877.jp","Info Master"
我怎样才能使其在excel中看起来还不错?
更新:
我尝试按照建议添加PHPExcel,但仍然给我同样的乱码输出。
我在这里包括了我的代码,也许有人可以帮助编辑代码。
控制器:
public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {
$sendTo = rawurldecode($sendTo);
$headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");
// Header
$header = str_replace(",", "", $headerArray);
$datas = implode(',', $header) . "\r\n";
// Body
$limit = 50000;
$start = 0;
do {
$list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
foreach($list as $body)
{
$email = //some codes to clean email
$url = // some codes to clean url
$datas .= '"' .$body["id"].'"'.",".'"' .$body["prefecture_id"].'"'.",".'"' .$body["industry_id"].'"'.",".'"' .$body["offset"].'"'.",".'"' .$body["name"].'"'.",".'"' .$email .'"'. ",".'"' .$body["tel"].'"'. ",".'"' .$body["fax"].'"'.",".'"' .$body["address"].'"'.",".'"' .$url.'"'.",".'"' .$body["flexible_1"].'"'.",".'"' .$body["flexible_2"].'"'.",".'"' .$body["flexible_3"].'"'.",".'"' .$body["flexible_4"].'"'.",".'"' .$body["flexible_5"].'"'.",".'"' .$body["sequence"].'"'.",".'"' .$body["del_flg"].'"'.",".'"' .$body["create_date"].'"'.",".'"' .$body["create_user"].'"'.",".'"' .$body["update_date"].'"'.",".'"' .$body["update_user"].'"'.",".'"' .$body["site_name"].'"'."\r\n";
}
$start += $limit;
}while(count($list) > 0);
$fileName = "listmaster_".date('YmdHis').".csv";
$csv_handler = fopen ('/var/www/citest/csv/'.$fileName,'w');
fwrite ($csv_handler,$datas);
fclose ($csv_handler);
}
public function download() {
log_message('debug', 'starting download.');
$file = $_GET['file'];
$filePath = '/var/www/citest/csv/'.$file;
if(!$file){ // file does not exist
die('file not found');
} else {
header('HTTP/1.1 200 OK');
header('Cache-Control: no-cache, must-revalidate');
header("Pragma: no-cache");
header("Expires: 0");
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=$file");
// read the file from disk
log_message('debug', 'reading file.');
readfile($filePath);
log_message('debug', 'reading file done');
}
}
更新2:
这是我如何使用PHPExcel做到的
require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel.php');
require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');
...
...
public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {
$sendTo = rawurldecode($sendTo);
//Create a new Object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
$headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");
// Header
$rowNumberH = 1; //set in which row title is to be printed
$colH = 'A'; //set in which column title is to be printed
foreach($headerArray as $h){
$objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
$colH++;
}
// Body
$limit = 50000;
$start = 0;
do {
$list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
$rowCount = 2; // set the starting row from which the data should be printed
log_message('debug', "Query: offset:{$start} limit:{$limit} done");
foreach($list as $body)
{
//$email =
//$url =
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $body['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $body['prefecture_id']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $body['industry_id']);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $body['offset']);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, $body['name']);
$objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, $email);
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, $body['tel']);
$objPHPExcel->getActiveSheet()->SetCellValue('H'.$rowCount, $body['fax']);
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount, $body['address']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount, $url);
$objPHPExcel->getActiveSheet()->SetCellValue('K'.$rowCount, $body['flexible_1']);
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount, $body['flexible_2']);
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, $body['flexible_3']);
$objPHPExcel->getActiveSheet()->SetCellValue('N'.$rowCount, $body['flexible_4']);
$objPHPExcel->getActiveSheet()->SetCellValue('O'.$rowCount, $body['flexible_5']);
$objPHPExcel->getActiveSheet()->SetCellValue('P'.$rowCount, $body['sequence']);
$objPHPExcel->getActiveSheet()->SetCellValue('Q'.$rowCount, $body['del_flg']);
$objPHPExcel->getActiveSheet()->SetCellValue('R'.$rowCount, $body['create_date']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$rowCount, $body['create_user']);
$objPHPExcel->getActiveSheet()->SetCellValue('T'.$rowCount, $body['update_date']);
$objPHPExcel->getActiveSheet()->SetCellValue('U'.$rowCount, $body['update_user']);
$objPHPExcel->getActiveSheet()->SetCellValue('V'.$rowCount, $body['site_name']);
$rowCount++;
}
$start += $limit;
}while(count($list) > 0);
$fileName = "listmaster_".date('YmdHis').".csv";
$objPHPExcel->getActiveSheet()->setTitle($fileName);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->setDelimiter(',');
$objWriter->save('/var/www/citest/csv/' . $fileName);
}
如@luhuiya所述,您可以使用phpexcel来获得正确的格式。
假设您已经使用composer安装了phpexcel。
这是一个工作示例:
<?php
require_once __DIR__ . '/vendor/autoload.php';
/*
You query your data into an array here
$data = ...
*/
$data = [
[ 'KN01001', '荳陦帙', 'admin@listmaster.com', 'List Master', '' ],
[ 'KN01002', '譌ュ譚セ', 'information@e877.jp', 'Info Master', '' ],
];
$phpXls = new PHPExcel();
// Fill worksheet from values in array
$phpXls->getActiveSheet()->fromArray($data, null, 'A1');
// Work on PHPExcel object, set worksheet metadata
// Change the ... parts according to your needs
$phpXls->getProperties()->setCreator("...")
->setLastModifiedBy("...")
->setTitle("...")
->setSubject("...")
->setDescription("...")
->setKeywords("...");
$phpXls->getActiveSheet()->setTitle('...');
// I saw in your examlpe data, that you can have long strings in some columns
// Therefore You can widen the excel columns in order to be readable at full length.
// Get Excel column range and dynamically resize columns
$highestColumn = $phpXls->getActiveSheet()->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
foreach (range(0, $highestColumnIndex) as $columnIndex) {
$phpXls->getActiveSheet()->getColumnDimensionByColumn($columnIndex)->setAutoSize(true);
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpXls->setActiveSheetIndex(0);
// Save Excel 2007 file
$xlsWriter = PHPExcel_IOFactory::createWriter($phpXls, 'Excel2007');
$xlsWriter->save('your_data.xlsx');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.