Peter
Peter

Reputation: 9143

Method to speed up reading the contents of a file

In a script I'm having I'm pulling a csv from a remote server using ftp. I save this file locally and then open the file. I loop through all the contents of the file matching a certain value against it. If it matches, the script can continue.

Enough talking. Lets show some code...

$filename = 'ftp://.....';
$localCsv = '/tmp/'.date('Ymd').'.csv';
if (!file_exists($localCsv)) {
    $content = file_get_contents($filename);
    file_put_contents($localCsv, $content);
}

Now that we have the file created. We can continue to loop.

$handle = fopen($localCsv, "r");
while(!feof($handle)) {
  $rows[] = fgets($handle);
}
fclose($handle);

$results = array();
foreach ($rows as $rid => $row) {
    $columns = explode("\t", $row);
    $results[$columns[2]] = $columns;
}

if (array_key_exists($searchValue, $results)) {
    ... Continue script ...
}

There is just one tiny little problem with this method. It's so slow it's almost going backwards.

Upvotes: 0

Views: 209

Answers (1)

BobbyTables
BobbyTables

Reputation: 4715

Heres all baked together, maybe thats faster?

$handle = fopen($localCsv, "r");
$results = array();
while(!feof($handle)) {
    $columns = explode("\t", fgets($handle));
    $results[$columns[2]] = $columns;
    if ($columns[2] == $searchValue) {
        //SEARCH HIT
    }
}
fclose($handle);

If thats not working you could try the csv-specific methods that are in PHP

Upvotes: 1

Related Questions