是否可以读取包含关键字的多行CSV文件


Can you read in multiple lines of CSV containing a keyword?

我完全是php的新手。我想知道是否有可能读取包含关键字的多行csv文件并在php中显示它们?

我有一个结构如下的csv文件:

keyword1, data, other data, etc
keyword2, another data, other etc
keyword1, something, something etc

所以我想在php页面中打印的是:

keyword1, data, other data, etc
keyword1, something, something etc

这可能吗?谢谢大家的回答

修改代码创建html表。没有测试过,如果不行请告诉我。

<?php
 $output = '<table>';
 $searchFor = "1124";
 $fp = fopen("data.csv", "r");
    // Read file

$matching_rows = array();
 while ( ($row = fgetcsv($fp,1000,",")) !== FALSE ) {
      // Search for keyword
      if ( (array_search( $searchFor,$row,TRUE) ) !== false ) {
           $matching_rows[] = '<tr><td>' . implode('</td><td>',$row) . '</td></tr>';
      }
 }
if(!empty($matching_rows) ) {
  $output = '<table><tbody>' . "'n" . implode("'n't",$matching_rows) . "'n" . '</tbody></table>';
}
echo '<div class="display">';
echo $output;
 echo '</div>';
?>
$results = array();
$handle = fopen("csvFile.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if( strpos ( $data , 'keyword1' ) !== false){
        $results[] = $data;
    }
}

我发现这对我的问题很有效。

<?php
 $output = "";
 $searchFor = "1124";
 $fp = fopen("data.csv", "r");
    // Read file
 $txt = fgets($fp);
 while ( !feof( $fp ) ) {
      // Search for keyword
      if ( strpos( $txt, $searchFor ) !== false ) {

           $output .= $txt.'<br />';
      }
      $txt = fgets($fp);
 }
echo '<div class="display">';
 echo $output;
 echo '</div>';
?>

然而,我将非常高兴,如果不是逗号分隔值,我可以加载这些html表,这样他们可以看起来更好一点。我试图将$output .=$txt与表标签连接起来,但在此配置中似乎只有断行有效。有什么线索可以告诉我如何做到这一点吗?欢呼:)