php中如何导入导出CSV格式的文件
2015-06-29 · 知道合伙人互联网行家
知道合伙人互联网行家
向TA提问 私信TA
php导入CSV文件:
$line_number = 0;
$handle = fopen("1.xls","r");
while ($data = fgetcsv ($handle, 100000, ",")) {
if($line_number == 0){
$line_number++;
continue;
}
//z这样就可以去掉表头的那一行
for ($i = 0; $i < count($data); $i++) {
$ziduan = $data[$i];
}
}
2.php导出CSV文件
header( "Cache-Control: public" );
header( "Pragma: public" );
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=txxx.csv");
header('Content-Type:APPLICATION/OCTET-STREAM');
ob_start();
$header_str = iconv("utf-8",'gbk',"信息id,标题,名称,电话,QQ,Email,内容,时间\n");
$file_str="";
$mysqli= new mysqli('localhost','root','','test');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql='select * from messages';
$mysqli->query("set names utf8 ;");
$result=$mysqli->query($sql);
if($result){
while ($row = mysqli_fetch_assoc($result)){
$file_str.= $row['id'].','.$row['title'].','.$row['name'].','."'{$row['telephone']}'".','.$row['qq'].','.$row['email'].','.str_ireplace(',',',',$row['content']).','.$row['retime']."\n";
}
}else{
echo "nonono!!!";
}
$file_str= iconv("utf-8",'gbk',$file_str);
ob_end_clean();
echo $header_str;
echo $file_str;
?>
$line_number = 0;
$handle = fopen("1.xls","r");
while ($data = fgetcsv ($handle, 100000, ",")) {
if($line_number == 0){
$line_number++;
continue;
}
//z这样就可以去掉表头的那一行
for ($i = 0; $i < count($data); $i++) {
$ziduan = $data[$i];
}
}
导出参考:
http://blog.sina.com.cn/s/blog_60b59c8e0100lv2o.html
使用fputcsv()可中已开启的文件中“存入”一行数组为CSV值。