Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn about the development of the project. In many cases, you need to import external CSV files into the database or export the data as CSV files, how can we achieve this? This article uses PHP and mysql to import and export CSV data.
Process for importing a CSV file: check the validity of the csv file (this document ignores) -> open the fields in the csv file and parse them.-> obtain the values of each field cyclically-> add them to the data table in batches-> complete.
If ($ action = 'import') {// import CSV
$ Filename = $ _ FILES ['file'] ['tmp _ name'];
If (empty ($ filename )){
Echo 'select the CSV file to import! ';
Exit;
}
$ Handle = fopen ($ filename, 'R ');
$ Result = input_csv ($ handle); // parse csv
$ Len_result = count ($ result );
If ($ len_result = 0 ){
Echo 'No data! ';
Exit;
}
For ($ I = 1; $ I <$ len_result; $ I ++) {// obtain Field Values cyclically
$ Name = iconv ('gb2312', 'utf-8', $ result [$ I] [0]); // Chinese Transcoding
$ Sex = iconv ('gb2312', 'utf-8', $ result [$ I] [1]);
$ Age = $ result [$ I] [2];
$ Data_values. = "('$ name',' $ sex', '$ age '),";
}
$ Data_values = substr ($ data_values, 0,-1); // remove the last comma
Fclose ($ handle); // close the pointer
$ Query = mysql_query ("insert into student (name, sex, age) values $ data_values"); // insert data tables in batches
If ($ query ){
Echo 'import successful! ';
} Else {
Echo 'import failed! ';
}
}
CSV import/export using PHP: Http://www.sucaihuo.com/php/324.html
PHP Import and Export csv1_demo .rar (3.32 KB download: 139 times)
AD: truly free, domain name + VM + enterprise mailbox = 0 RMB