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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?