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 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程