PHP read CSV Large file Import Database method

Source: Internet
Author: User
Tags php mysql import database
This article mainly introduces PHP read CSV large file Import database method, interested in the friend's reference, I hope to help you.

How does PHP read the CSV large file and import the database?

For millions of data volumes of CSV file, the file size may reach hundreds of m, if simply read, it is likely to have a time-out or a card-dead phenomenon.

Batch processing is necessary in order to successfully import data from a CSV file into a database.

The following function reads a few rows of data specified in a CSV file:

/** * Csv_get_lines reads a few rows of data in the CSV file * @param $csvfile CSV file path * @param $lines Read rows * @param $offset starting lines * @return Array * */function csv_get_lines ($csvfile, $lines, $offset = 0) {if (! $fp = fopen ($csvfile, ' R ')) {return false;} $i = $j = 0;wh Ile (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 ', ten, 2000000);p Rint_r ($data);

The function mainly adopts the idea of line positioning, and the file pointer positioning is achieved by skipping the number of start lines.

As for how data is put into storage, this article is no longer detailed.

The above function tests the files within 500M, runs smoothly, and does not test for larger files, please use them or improve them.

This PHP read CSV large file Import database instance is a small part of the whole content to share to everyone, I hope to give you a reference.

Related recommendations:

How PHP automatically backs up database tables

How PHP mysql database encapsulates classes

How PHP encapsulates a mongodb database

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.