douhuang7263 2014-08-20 14:11 采纳率: 100%
浏览 97
已采纳

使用PHP查找CSV文件中是否存在值

This is my code to check if a row of my .csv file contains a specific name, but it does not work.

I think it has something to do with the if statement.

$file_handle = fopen("sources.csv", "r");

while (!feof($file_handle) ) {

    $line_of_text = fgetcsv($file_handle, 1024);

    if ($line_of_text[0] = 'paul') {
        echo 'Found';
    }
}
fclose($file_handle);

I am trying to check in sources.csv files, for the name 'Paul' .

I can't use a database like MySQL for technical reasons.

  • 写回答

3条回答 默认 最新

  • dongxianghui3709 2014-08-20 15:16
    关注

    Since you haven't provided a sample of your file, am submitting the following as an alternative.

    Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.

    if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')

    Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.

    Paul, Larry, Robert
    

    Code:

    <?php
    $search      = "Paul";
    $lines       = file('sources.csv');
    $line_number = false;
    
    while (list($key, $line) = each($lines) and !$line_number) {
    
       $line_number = (strpos($line, $search) !== FALSE);
    
    }
    
    if($line_number){
    
       echo "Results found for " .$search;
    
    }
    
    else{
       echo "No results found for $search";
    }
    

    Footnotes:

    For a case-insensitive search, use stripos()

    $line_number = (stripos($line, $search) !== FALSE);
    

    Row number found on...

    To give you the row's number where it was found:

    $line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
    

    or (case-insensitive)

    $line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
    

    then just echo $line_number;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,