這篇文章主要介紹了PHP實現CSV文件的導入和導出類,實例分析了php針對csv文件的操作技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了PHP實現CSV文件的導入和導出類。分享給大家供大家參考。具體如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 <?php /** * CSV 文件處理類 */ class Csv{ public $csv_array; //csv數組數據 public $csv_str; //csv文件數據 public function __construct($param_arr, $column){ $this->csv_array = $param_arr; $this->path = $path; $this->column = $column; } /** * 導出 * */ public function export(){ if(empty($this->csv_array) || empty($this->column)){ return false; } $param_arr = $this->csv_array; unset($this->csv_array); $export_str = implode(',',$param_arr['nav'])."n"; unset($param_arr['nav']); //組裝數據 foreach($param_arr as $k=>$v){ foreach($v as $k1=>$v1){ $export_str .= implode(',',$v1)."n"; } } //將$export_str導出 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(); // $file_str= iconv("utf-8",'gbk',$export_str); ob_end_clean(); echo $export_str; } /** * 導入 * */ public function import($path,$column = 3){ $flag = flase; $code = 0; $msg = '未處理'; $filesize = 1; //1MB $maxsize = $filesize * 1024 * 1024; $max_column = 1000; //檢測文件是否存在 if($flag === flase){ if(!file_exists($path)){ $msg = '文件不存在'; $flag = true; } } //檢測文件格式 if($flag === flase){ $ext = preg_replace("/.*.([^.]+)/","$1",$path); if($ext != 'csv'){ $msg = '只能導入CSV格式文件'; $flag = true; } } //檢測文件大小 if($flag === flase){ if(filesize($path)>$maxsize){ $msg = '導入的文件不得超過'.$maxsize.'B文件'; $flag = true; } } //讀取文件 if($flag == flase){ $row = 0; $handle = fopen($path,'r'); $dataArray = array(); while($data = fgetcsv($handle,$max_column,",")){ $num = count($data); if($num < $column){ $msg = '文件不符合規格真實有:'.$num.'列數據'; $flag = true; break; } if($flag === flase){ for($i=0;$i<3;$i++){ if($row == 0){ break; } //組建數據 $dataArray[$row][$i] = $data[$i]; } } $row++; } } return $dataArray; } } $param_arr = array( 'nav'=>array('用戶名','密碼','郵箱'), array(0=>array('xiaohai1','123456','[email protected]'), 1=>array('xiaohai2','213456','[email protected]'), 2=>array('xiaohai3','123456','[email protected]') )); $column = 3; $csv = new Csv($param_arr, $column); //$csv->export(); $path = 'C:Documents and SettingsAdministratorTemptxxx.csv'; $import_arr = $csv->import($path,3); var_dump($import_arr); ?>希望本文所述對大家的php程序設計有所幫助。