|
<? Php
/**
* CSV file processing class
*/
Class Csv {
Public $ csv_array; // csv array data
Public $ csv_str; // csv file data
Public function _ construct ($ param_arr, $ column ){
$ This-> csv_array = $ param_arr;
$ This-> path = $ path;
$ This-> column = $ column;
}
/**
* Export
**/
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']);
// Assemble data
Foreach ($ param_arr as $ k => $ v ){
Foreach ($ v as $ k1 => $ v1 ){
$ Export_str. = implode (',', $ v1). "n ";
}
}
// Export $ 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;
}
/**
* Import
**/
Public function import ($ path, $ column = 3 ){
$ Flag = flase;
$ Code = 0;
$ Msg = 'unprocessed ';
$ Filesize = 1; // 1 MB
$ Maxsize = $ filesize * 1024*1024;
$ Max_column = 1000;
// Check whether the file exists
If ($ flag === flase ){
If (! File_exists ($ path )){
$ Msg = 'file does not exist ';
$ Flag = true;
}
}
// Check the file format
If ($ flag === flase ){
$ Ext = preg_replace ("/. *. ([^.] +)/", "$1", $ path );
If ($ ext! = 'Csv '){
$ Msg = 'only CSV files can be imported ';
$ Flag = true;
}
}
// Check the file size
If ($ flag === flase ){
If (filesize ($ path)> $ maxsize ){
$ Msg = 'imported file cannot exceed '. $ maxsize.' B file ';
$ Flag = true;
}
}
// Read the file
If ($ flag = flase ){
$ Row = 0;
$ Handle = fopen ($ path, 'R ');
$ DataArray = array ();
While ($ data = fgetcsv ($ handle, $ max_column ,",")){
$ Num = count ($ data );
If ($ num <$ column ){
$ Msg = 'The file does not meet the actual specifications: '. $ num.' column data ';
$ Flag = true;
Break;
}
If ($ flag === flase ){
For ($ I = 0; $ I <3; $ I ++ ){
If ($ row = 0 ){
Break;
}
// Set up data
$ DataArray [$ row] [$ I] = $ data [$ I];
}
}
$ Row ++;
}
}
Return $ dataArray;
}
}
$ Param_arr = array (
'Nav' => array ('username', 'Password', 'mailbox '),
Array (0 => array ('xiaohai1', '20140901', 'xiaohai1 @ zhongsou.com '),
1 => array ('xiaohai2 ', '000000', 'xiaohai2 @ zhongsou.com '),
2 => array ('xiaohai3 ', '123', 'xiaohai3 @ zhongsou.com ')
));
$ Column = 3;
$ Csv = new Csv ($ param_arr, $ column );
// $ Csv-> export ();
$ Path = 'C: \ Documents and Settings \ Administrator \ Temp \ txxx.csv ';
$ Import_arr = $ csv-> import ($ path, 3 );
Var_dump ($ import_arr );
?>
|