Php csv File Import/Export Function

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.