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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?