-2

I'd like to find a match of a string in a CSV file in PHP 5.

There is, for me, 2 ways to do it :

  • First : Get all occurences from the csv file, then check if my string exist in the array.
  • Second : For each line of my CSV file, check if it matches. If it does, end the loop.

Which is the best way to do it ? There is a lot of line in my CSV file so I care about performance.

If you know some clues about it, I'll be glad to heard it :)

5
  • Great, you got 2 ways to do it. Try them and come back to us and edit your question if your attempt fails. Commented Oct 1, 2018 at 8:56
  • Since your first approach is basically second in a loop, it should be pretty clear what makes more sense in terms of performance and resource usage w/o need to ask here. Commented Oct 1, 2018 at 8:57
  • You probably need to take stuff like delimiter, enclosure and escaping characters into account to not get false matches (or overlook one, because it contains one of the aforementioned where you didn’t expect it) - so you should use the proper methods provided for that by PHP to begin with. fgetcsv reads single lines of data to begin with, so breaking out of the loop when you found what you need would be quite easy using that one. Commented Oct 1, 2018 at 8:59
  • @misorude Perfect, didn't know this function ! Others, instead of saying nothing, do something usefull :) Commented Oct 1, 2018 at 9:02
  • 2
    Possible duplicate of PHP Find String in CSV file Commented Oct 1, 2018 at 9:07

2 Answers 2

2

For large csv files, you should use fgetcsv (http://php.net/manual/en/function.fgetcsv.php).

$handle = fopen('filename.csv', 'r'))

if($handle)
{
    while(($line = fgetcsv($handle)) !== false)
    {
        // do whatever with csv data
    }
    fclose($handle);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The fastest way would be to read the file as a string, and then find the first occurrence of the word, something like this:

$file = file_get_contents('file_name.csv');

if (strpos($file, 'your string') !== false) {
   // Found it
}

// Use mb_strpos for UTF-8
if (mb_strpos($file, 'your string') !== false) {
   // Found it
}

If it is something more complex then your best bet is to use regex and preg_match.

UPDATE:

You can also go with this approach and check line by line, this way you won't store the whole 300K line file in your memory:

$file = new SplFileObject('file_name.csv');

while($file->valid()) {
    if (strpos($file->current(), 'your string') {
        // Found it
        break;
    }
    $file->next();
}

1 Comment

Thanks for the answer. Isn't to heavy if I have like 300 000 rows to get all the content in once ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.