如何有效读取和比较上传到服务器的大量数据?

时间:2019-07-02 17:30:59

标签: php

我正在编写一个简单的脚本,该脚本比较两个文件并返回文件之间的匹配项。这些文件是CSV和txt文件,仅包含用户的电子邮件。我需要比较这些文件并返回一个单独的文件,并在文件之间匹配电子邮件。我的脚本可以处理少量数据(例如1000封电子邮件)并返回正确的结果。但是,一旦数据过大(超过1000封电子邮件),脚本将永远无法完成,并且不返回任何内容。

我试图一次全部加载数据,然后用PHP读取它,但这会导致崩溃。所以目前,我只是让脚本逐行读取文件,然后关闭文件。当数据文件太大时,这不会给我带来任何错误,但也不会给我带来任何结果。

我想指出,出于测试目的,我对文件'a.txt'和'b.txt'进行了硬编码,但通常我会使用$ _FILES访问它。这些文件是由用户通过表单上传的,我将其从temp文件夹移至uploads /文件夹。

这是脚本:

<?php
// debug helper function
function debug_to_console($data)
{
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "console.log( 'Debug Objects: " . $output . "' );";
}

if (isset($_POST['comcsvb'])) {
    // Allow automatic detection of line endings
    ini_set('auto_detect_line_endings', true);

    //Array that will hold the lines that match
    $matches = array();

    //Opening the two files on read mode
    $a_handle = fopen('uploads/a.txt', "r");
    $b_handle = fopen('uploads/b.txt', "r");

    //Iterate the first file one line at the time
    while (($a_line = fgets($a_handle)) !== false) {

        //For each line on the first file, iterate the second file a line at a time
        while (($b_line = fgets($b_handle)) !== false) {

            //remove any whitespace or new line from the beginning or the end of string
            $b_keyword = trim($b_line);

            //Check if the first file's line contains the second file's on any position
            // using case insensitive comparison
            if (preg_match("/$b_keyword/i", trim($a_line))) {
                //Add the domain line to the matches array
                $matches[] = $a_line;
            }
        }
        //Set the pointer to the beginning of the second file
        rewind($b_handle);
    }

    //Release the resources
    fclose($a_handle);
    fclose($b_handle);

    var_dump($matches);
}

我希望输出是位于两个文件中的电子邮件(数据)列表。当前输出为空。我假设它会永远加载。我还应该提到,每封电子邮件都在新行中。

email1@test.com
email2@test.com
email3@test.com

等等。

0 个答案:

没有答案