Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Find String in CSV file

Tags:

arrays

php

I've got a large flat file of usernames and emails in the following format:

"username", "email"
"username", "email"
"username", "email"

etc...

I need to take the email and search for the username, but for some reason it will not return a result. It works if I search opposite.

$string = "[email protected]";
$filename = "user_email.txt";
        $h = fopen("$filename","r");
        $flag=0;

        while (!feof ($h)) {
            $buffer = fgets($h);
            $thisarray = split(",", $buffer);

            if ($string == str_replace('"','', $thisarray[1])) { 
                $i = 1;
                $i++;
                echo '<td bgcolor="#CCFFCC"><b style="color: maroon">' . str_replace('"','',$thisarray[0]). '</b></td>';

                }   

Any ideas? Thanks!

like image 725
Ed. Avatar asked Jun 21 '11 14:06

Ed.


2 Answers

As per reko_t's suggestion: Use fgetcsv to read individual lines of csv into arrays, until you find one where the second element matches your search term. The first element then is the username. Something like:

<?php
function find_user($filename, $email) {
    $f = fopen($filename, "r");
    $result = false;
    while ($row = fgetcsv($f)) {
        if ($row[1] == $email) {
            $result = $row[0];
            break;
        }
    }
    fclose($f);
    return $result;
}
like image 101
tdammers Avatar answered Oct 11 '22 08:10

tdammers


I truly believe that all examples in other answers works!
But all they are slow, because all of them travers each line in csv file...
I have another example how to find desired string:

$command = sprintf("grep '%s,%s' -Er %s", $userName, $email, $file);
$result = `$command`;

Yes it some kind of dark matter, but it really works and it really fast!

like image 40
cn007b Avatar answered Oct 11 '22 06:10

cn007b