php导入导出CSV格式的数据

来源:互联网 发布:c语言谭浩强电子版 编辑:程序博客网 时间:2024/04/29 11:42


1.新建html页面

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>    <form id="addform" action="do.php?action=import" method="post" enctype="multipart/form-data">        <p> 请选择要导入的CSV文件:<br/> <input type="file" name="file"><input type="submit" class="btn" value="导入CSV"> <input type="button" class="btn" value="导出CSV" onclick="window.location.href='do.php?action=export'">        </p>    </form></body></html>


2.处理的php页面

 

<?phprequire('conn.php');function input_csv($handle){$out=array();$n=0;while($data=fgetcsv($handle,10000)){$num=count($data);for($i=0;$i<$num;$i++){$out[$n][$i]=$data[$i];}$n++;}return $out;}function export_csv($filename,$data){header("Content-type:text/csv");header("Content-Disposition:attachment;filename=".$filename);header('Cache-Control:must-revalidate,post-check=0,pre-check=0');header('Expires:0');header('Pragma:public');echo $data;}$action=$_GET['action'];if($action=='import'){    $filename=$_FILES['file']['tmp_name'];if(empty($filename)){echo "请选择要导入的CSV文件!";exit;}$handle=fopen($filename,'r');$result=input_csv($handle);$len_result=count($result);if($len_result==0){echo '没有任何数据';exit;}for($i=1;$i<$len_result;$i++){$id=htmlspecialchars($result[$i][0]);$name=htmlspecialchars($result[$i][1]);$sex=htmlspecialchars($result[$i][2]);$age=htmlspecialchars($result[$i][3]);$data_values.="('$name',$sex,$age),";}$data_values=substr($data_values,0,-1);fclose($handle);$query=mysql_query("insert into student(name,sex,age) values $data_values");//批量插入数据表echo "insert into student(name,sex,age) values $data_values";if($query){echo "导入成功!";}else{echo '导入失败!';}}else if($action=='export'){ $result=mysql_query("select * from student order by id asc"); $str="学号,姓名,性别,年龄\n"; $str=iconv('utf-8','gb2312',$str); while($row=mysql_fetch_array($result)){$id=iconv('utf-8','gb2312',$row['id']);$name=iconv('utf-8','gb2312',$row['name']);$sex=iconv('utf-8','gb2312',$row['sex']);$str.=$id.",".$name.",".$sex.",".$row['age']."\n"; } $filename='20140925.csv'; //echo $str; export_csv($filename,$str);}?>
0 0
原创粉丝点击