Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 263
  • Last Modified:

PHP: Most efficient way to remove the first line from a file

Using PHP. what is the most efficient way to remove the first line from a text file?
0
hankknight
Asked:
hankknight
  • 2
3 Solutions
 
Hugh McCurdyCommented:
I don't know of a way except to read each line from the file and write lines 2 through n to a different file followed by delete and rename.

Perhaps someone else has some magic but I'd be surprised.
0
 
Ray PaseurCommented:
The most efficient way would be to not create the first line at all.  So modifying the code that creates the file might be one good option

But if it is already there, then the process would be what hmccurdy described.  You might want to take a backup before you start since this is an irrevocable change in the file system.  You would also want to be sure you did not accidentally rerun this process.  That argues for a separate directory to hold the new files.

Pidgin code:

fopen
fread // DISCARD FIRST RECORD
while (!feof){
  fread
  fwrite
}
unlink old
rename new

If the files are relatively small and will fit in memory, you can use file() to read the file into an array.

$arr = file(path/to/file)
unset($arr[0])
$str = implode(PHP_EOL, $arr)
file_put_contents($str)
0
 
Hugh McCurdyCommented:
Good point, Ray.

Just occurred to me that it might be a CSV file.  Is it a CSV file?
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now