PHP在CSV文件中查找字符串 [英] PHP Find String in CSV file

查看:174
本文介绍了PHP在CSV文件中查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的平面文件名,其中包含以下格式的用户名和电子邮件:

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

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

等...

我需要接收电子邮件并搜索用户名,但是由于某种原因,它不会返回结果.如果我搜索相反,它会起作用.

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 = "user_email@something.com";
$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>';

                }   

有什么想法吗?谢谢!

推荐答案

按照reko_t的建议:使用fgetcsv将csv的各个行读取到数组中,直到找到第二个元素与搜索词匹配的位置.然后,第一个元素是用户名.像这样:

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

这篇关于PHP在CSV文件中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆