http://blog.csdn.net/thefirstwind/archive/2008/05/09/2422715.aspx 很多人通过拼字符串,直接使用fwrite来写CSV文件,这样固然没有错,但是如果遇到允许引号和逗号出现的情况,恐怕就显得非常麻烦了。 例如: $csvDate = 中文,日文,韩文,西班牙','文,阿拉
http://blog.csdn.net/thefirstwind/archive/2008/05/09/2422715.aspx
很多人通过拼字符串,直接使用fwrite来写CSV文件,这样固然没有错,但是如果遇到允许引号和逗号出现的情况,恐怕就显得非常麻烦了。
例如:
$csvDate = "中文,日文,韩文,西班牙','文,阿拉伯文";
$srcDir = '/workspace/CSVList';
$srcFile = $srcDir.date("Ymd").".csv";
if(!is_dir($srcDir)){
$fh = fopen($srcFile,'wb');
fwrite($fh,$csvDate);
fclose($fh);
}
我们想要得CSV文件是这样的格式
中文 | 日文 | 韩文 | 西班牙','文 | 阿拉伯文 |
但是由于,西班牙文中有单引号和逗号
实际上在Excel中是这样的
中文 | 日文 | 韩文 | 西班牙' | 文 | 阿拉伯文 |
解决方法一般来说就是使用转义符来进行赋值,不过如果遇到海量数据的情况下,这样的办法是不可取的。
下面推荐使用array_push和fputcsv相结合的方法来解决该问题。
这里通过程序来说明:
$srcDir = '/workspace/UnLockList/';
( !is_dir($srcDir) ) && (mkdir($srcDir, 0777) && chmod($srcDir,0777)) ;
$srcFile = $srcDir . date("Ymd") . '.csv';
$rs0 = GetCSVData($PRDBConn); //UnLockTN_Request返回的是二维数组
$fh = fopen($srcFile, 'wb');
if(count($rs0)){
fputcsv($fh,split(',',"申請ID,機種名,EB-№,申請№,部品名,LockUser"));
foreach($rs0 as $line0 ){
fputcsv($fh,$line0);
}
}
fputcsv($fh,array());
fclose($fh);
chmod($srcFile,0666);
function GetCSVData ($PRDBConn){
$RETURN_ARRAY = array();
//数据库连接
.....
.....
$RS01 = 记录集;
foreach ($RS01 AS $ROW01){
$line = array();
array_push($line,$ROW01["ID"]);
array_push($line,$ROW01["NAME"]);
array_push($line,$ROW01["NO"]);
.......
array_push($RETURN_ARRAY,$line);
}
return $RETURN_ARRAY;
}
如上程序所示,就可以解决大量数据输出成CSV文件中,出现特殊意义字符,导致输出CSV文件格式异常的问题了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor