Question

I'm trying to read the file and take the first line of content and write it at the end. Then I want to rewind back to the beginning of the file and remove the content that part that I just wrote at the end.

$pklist = "pklist.txt";
$pkhandle = fopen($pklist, 'a+');
$pkdata = fread($pkhandle, 5);
fwrite($pkhandle, "\n" . $pkdata);
rewind($pkhandle);

So far this is working to read the first 5 characters and then append them at the end. But after reading the PHP documentation and looking around SO I'm still not sure how to just chop off a set number of characters from the beginning after I rewind.

btw. My text file is just a list of 5 digit numbers with a line break at the end of each.

Was it helpful?

Solution

<?php
$f = 'pklist.txt';
$fp = fopen($f, 'r+');

$data = fgets($fp);
$contents = fread($fp, filesize($f));
fseek($fp, 0);
fwrite($fp,$contents);
fwrite($fp,$data);
fclose($fp);
?>

That should work..

Open file using r+

Read first line and store to $data

Read the rest and store to $contents (fread will stop once end of file is reach)

Rewind to beginning of file

Write $contents

Write $data

Close file

Note: Also, if you want just a fixed number of characters instead of the entire line. Just change fgets to something like fgets($fp,5) to only move 5 chars.

OTHER TIPS

If the file is not too big, you can use these calls:

$file = file($pklist);                // read the file line by line
$file[] = $file[0];                   // append first line to the end
$file[0] = null;                      // delete line 0
                                      // if not working, use unset($file[0]);
$file = array_filter($file);          // remove empty elements
$file = implode("\n", $file);         // array to string, concat by 1 newline
file_put_contents($pklist, $file);    // write contents back to file

The file get's loaded into memory thus not suitable for very big files.. but simplest usage for files of size < 1GB.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top