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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同