duanma8207 2014-10-15 19:19
浏览 28
已采纳

在php中只读取文件中的行号

I'm trying to just read even numbered lines from a text file. I know about the modulo(%) operator which I could put in a loop and attain the desired result, but somehow I can't figure out how to put it to use here.

Here is the code I have:

<?php    
$url   = "somedomain/something";
$lines = file('text.txt', FILE_IGNORE_NEW_LINES);

foreach ($lines as $line_num => $line) {

    echo "<br />
" . "Line #<b>{$line_num}</b>  :" . (htmlspecialchars($line));
    $dom = new DOMDocument;
    $dom->loadHTMLFile($url . $line);
    foreach ($dom->getElementsByTagName('p') as $node) {
        // do stuff with $node
        echo $node->nodeValue, "
";

    }
}    
?>
  • 写回答

2条回答 默认 最新

  • dtjw6660 2014-10-15 19:24
    关注

    Use the modulo operator on the line number. If it's 0 then the line is even, if it's 1 then the line is odd (these line numbers are zero-based -- swap them if you want one-based counting). Then use the continue statement to skip the rest of the loop body and go to the next line.

    foreach ($lines as $line_num => $line) {
        if ($line_num % 2 == 1) {
            continue; // Skip odd lines
        }
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥20 双系统开机引导中windows系统消失问题?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方
  • ¥15 关于生产日期批次退货退款,库存回退的问题
  • ¥15 手机应用的时间可以修改吗
  • ¥15 docker 运行OPEN-webui异常
  • ¥15 麒麟系统如何删除光盘刻录痕迹
  • ¥15 recipe通过gem协议传的是什么
  • ¥15 TS2307: Cannot find module 'cc'.
  • ¥15 100小时学会sap 书上pp章节5.22,标准成本计算逻辑?