-
- /*
- * PHP code to export MySQL data to CSV
- *
- * Sends the result of a MySQL query as a CSV file for download
- * Easy to convert to UTF-8.
- */
-
- /*
- * establish database connection
- */
-
- $conn = mysql_connect('localhost', 'login', 'pass') or die(mysql_error());
- mysql_select_db('database_name', $conn) or die(mysql_error($conn));
- mysql_query("SET NAMES CP1252");
- /*
- * execute sql query
- */
- $query = sprintf('SELECT field1,field2 FROM table_name');
- $result = mysql_query($query, $conn) or die(mysql_error($conn));
- /*
- * send response headers to the browser
- * following headers instruct the browser to treat the data as a csv file called export.csv
- */
- header('Content-Type: text/csv; charset=cp1252');
- header('Content-Disposition: attachment;filename=output.csv');
- /*
- * output header row (if atleast one row exists)
- */
-
- $row = mysql_fetch_assoc($result);
- if ($row) {
- echocsv(array_keys($row));
- }
-
- /*
- * output data rows (if atleast one row exists)
- */ 导出csv文件
- while ($row) {
- echocsv($row);
- $row = mysql_fetch_assoc($result);
- }
-
- /*
- * echo the input array as csv data maintaining consistency with most CSV implementations
- * - uses double-quotes as enclosure when necessary
- * - uses double double-quotes to escape double-quotes
- * - uses CRLF as a line separator
- */
-
- function echocsv($fields)
- {
- $separator = '';
- foreach ($fields as $field) {
- if (preg_match('/\r|\n|,|"/', $field)) {
- $field = '"' . str_replace('"', '""', $field) . '"';
- }
- echo $separator . $field;
- $separator = ',';
- }
- echo "rn";
- }
- ?>
复制代码
2. PHP import and export csv file classes
php implements the import and export classes of csv files.
Code:
-
- /**
- *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; //1MB
- $maxsize = $filesize * 1024 * 1024;
- $max_column = 1000;
-
- //Detect whether the file exists
- if($flag === flase){
- if(!file_exists($path)){
- $msg = 'File does not exist';
- $flag = true;
- }
- }
- //Detect file format
- if ($flag === flase){
- $ext = preg_replace("/.*.([^.]+)/","$1",$path);
- if($ext != 'csv'){
- $msg = 'Only CSV format files can be imported';
- $flag = true;
- }
- }
- //Detect file size
- if($flag === flase){
- if(filesize($path)> $maxsize){
- $msg = 'The imported file must not 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 specifications and actually contains: '.$num.' column data';
- $flag = true;
- break;
- }
- if($flag === flase){
- for($i=0;$i<3;$i++){
- if($row == 0){
- break;
- }
- //Build data
- $dataArray[$row][$i] = $data[$i];
- }
- }
- $row++;
- }
- }
- return $dataArray;
- }
- }
- $param_arr = array(
- 'nav' =>array('username','password','email'),
- array(0=>array('xiaohai1','123456','xiaohai1@jbxue.com'),
- 1=> array('xiaohai2','213456','xiaohai2@jbxue.com'),
- 2=>array('xiaohai3','123456','xiaohai3@jbxue.com')
- ));
- $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);
- ?>
Copy code
|