Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

arrays - PHP Find String in CSV file

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...