PHP reads large CSV files and imports them to the database
Source: Internet
Author: User
PHP reads large CSV files and imports them to the database. how does PHP read large CSV files and import them to the database?
For CSV files with millions of data records, the file size may reach several hundred MB. if you simply read the file, it is likely that the file times out or gets stuck.
Batch processing is necessary to successfully import the data in the CSV file into the database.
The following function reads the specified rows of data in a CSV file:
/*** Csv_get_lines reads certain rows of data in the CSV file * @ param $ csvfile csv file path * @ param $ lines read rows * @ param $ offset start row * @ return array * */function csv_get_lines ($ csvfile, $ lines, $ offset = 0) {if (! $ Fp = fopen ($ csvfile, 'r') {return false;} $ I = $ j = 0; while (false! ==( $ Line = fgets ($ fp) {if ($ I ++ <$ offset) {continue;} break ;}$ data = array (); while ($ j ++ <$ lines )&&! Feof ($ fp) {$ data [] = fgetcsv ($ fp);} fclose ($ fp); return $ data ;}
Call method:
$ Data = csv_get_lines ('path/bigfile.csv ', 10,200 0000 );
Print_r ($ data );
The function uses the line locating method to locate the file pointer by skipping the starting number of lines.
This article will not detail how to import data to Alibaba Cloud.
The above functions have been tested for files within MB and run smoothly. for larger files, please use or improve them as appropriate.
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.