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 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭