drmticpet66231422 2015-10-26 07:30
浏览 55
已采纳

从php中的csv文件返回第n行

I have a csv file and have created the code to read the whole file into a table thus:

$table = "<table id='availabilitytableData'>

";

$f = fopen("assets/temp/test.csv", "r");

while (($line = fgetcsv($f)) !== false) {

$table .= "<tr>";

foreach ($line as $cell) {
$table .= "<td style='font-size:9pt;'>" . htmlspecialchars($cell) . "</td>";
}

$table .= "</tr>
";
}

fclose($f);
$table .= "
</table>";
return $table;

What is the best approach to select say just the 4th row from the csv file? I have tried various approaches along the lines of

$line = file($f);//file in to an array
return $line[4];

which gives me the line I want but not in a formatted table. Other code snippets e.g. like this give clues but I can't seem to adapt them to my purpose. Bit stuck here I'm afraid any pointers are most welcome

  • 写回答

1条回答 默认 最新

  • douxing6434 2015-10-26 08:04
    关注

    What about something nice and simple like this:

    $lineNo = 1;  //initialise a pointer
    
    while (...) {
    
        if($lineNo == 4){
    
            //output line 4
    
            break;  //to prevent any more looping after line 4
        }
    
        $lineNo++;  //increment the pointer
    }
    

    Option 2

    Or.. ..just extract line 4 from $line and dont bother with a loop.

    $line = fgetcsv($f));
    
    $line4 = $line[3];  //arrays are zero-indexed
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改