Example of PHP reading and processing large CSV files by line

Source: Internet
Author: User
    1. /**
    2. * Csv_get_lines reads a few rows of data from a CSV file
    3. * @param $csvfile CSV file path
    4. * Number of rows @param $lines read
    5. * Number of start lines @param $offset
    6. * @return Array
    7. * * */bbs.it-home.org
    8. function Csv_get_lines ($csvfile, $lines, $offset = 0) {
    9. if (! $fp = fopen ($csvfile, ' R ')) {
    10. return false;
    11. }
    12. $i = $j = 0;
    13. while (false!== ($line = fgets ($fp))) {
    14. if ($i + + < $offset) {
    15. Continue
    16. }
    17. Break
    18. }
    19. $data = Array ();
    20. while (($j + + < $lines) &&!feof ($fp)) {
    21. $data [] = Fgetcsv ($FP);
    22. }
    23. Fclose ($FP);
    24. return $data;
    25. }
Copy Code

Call Method:

    1. $data = Csv_get_lines (' path/bigfile.csv ', 10, 2000000);
    2. Print_r ($data);
Copy Code

The function mainly adopts the idea of line positioning, and the file pointer positioning is achieved by skipping the number of start lines. The above function tests the files within 500M, runs smoothly, and does not test for larger files, please use them or improve them.

  • 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.