Home > OS >  Read text from .txt file started from other line php laravel
Read text from .txt file started from other line php laravel

Time:12-29

how can i read file from input file txt from certain line, example from line prefix AT on php example

can u help to continue my script `

  $data = $request->file('file');
        $filetmp = $data->getRealPath();
        $readfile = file_get_contents($filetmp);
        $files = fopen($filetmp,"r");
        $filedata = fread($files,filesize($filetmp));
        fclose($files);
        dd($filedata);

CodePudding user response:

Convert the lines into an array and discard all before your desired text like so:

$data = $request->file('file');
$filetmp = $data->getRealPath();

$filedata = File::get($filetmp);

// Convert into an array of lines
$lines = explode("\n", $filedata);

// discard lines before the first 'AT' 
$lines = array_slice($lines, strpos($lines, 'AT'));

foreach ($lines as $line) {
    // do something with the line of text
    echo $line . "\n";
}

CodePudding user response:

$file=$request->file('file');
$content=File::get($file->getRealPath());
$lines = explode("\n", $content);
$lines=array_slice($lines,
 array_keys(
  array_filter( 
   function($item){
   return strpos($item,'AT') ;
   }))[0]

  );
  • Related