doudi8231 2017-04-24 06:38
浏览 84
已采纳

如何在php中转到文件的第一行?

I am reading the file and getting the particular line if there is a match for the searched string. There are bunch of strings to be searched which are stored in a array. I cant be opening the file every time when i loop through the array to get the string. But want to go to the first line of the file and start searching again. The file contains around 15k lines. If i open the file every time(inside the loop) its working fine. but if the open the file outside the loop. Only the first matched string line is returned.

$scheme_code = 
array("106212","112422","114239","104685","100122","118191","131666");
foreach($scheme_code as $searchthis) {

        $handle = @fopen("myfile", "r"); 


        //DONT WANT TO DO THE ABOVE LINE FOR EVERY ITERATION

        if ($handle)
        {
            //echo "handle open"."<br>";
            while (!feof($handle))
            {

                $buffer = fgets($handle,4096);
                if(strpos($buffer, $searchthis) !== FALSE){
                    $matches[] = $buffer;
                }                       
            }               
        }       
    }

But want to do something like this

$handle = @fopen("Myfile", "r"); 
foreach(){
   // inside foreach 
   //go to the first line of the file
}
fclose($handle);

EDIT - I tried rewind(). I got the notice "rewind(): stream does not support seeking"

  • 写回答

1条回答 默认 最新

  • dsogx84602 2017-04-24 06:42
    关注

    Here you can use file() function which will give you complete array of lines and after that you can match line by line without using your IO resource everytime by fopen.

    <?php
    
    $linesArray = file("/path/to/your/file.txt"); 
    foreach($linesArray as $line){
       // do the stuff or matching you want to perform line by line on $line
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算