Reversing A text file using PHP
I have a file that is sorted using natsort()...(In ascending order)
开发者_JS百科But actually i want to sort it in descending order..
I mean the last line of document must be first line and vice versa
Pls let me know is there any function or snippet to achive this..
I'm not that good at php, Appreciate all responses irrespective of quality...Thank You
use natsort() and than use function array_reverse()
.
Also refer link
PHP Grab last 15 lines in txt file
it might help you.
array_reverse will give the contents in descending order
$reverse = array_reverse($array, true);
Whilst not the most efficient approach for a large text file, you could use file, array_reverse and file_put_contents to achieve this as follows...
<?php
// Fetch each line from the file into an array
$fileLines = file('/path/to/text/file.txt');
// Swap the order of the array
$invertedLines = array_reverse($fileLines);
// Write the data back to disk
file_put_contents('/path/to/write/new/file/to.txt', $invertedLines);
?>
...to achieve what you're after.
For longer files:
<?php
function rfopen($path, $mode)
{
$fp = fopen($path, $mode);
fseek($fp, -1, SEEK_END);
if (fgetc($fp) !== PHP_EOL) fseek($fp, 1, SEEK_END);
return $fp;
}
function rfgets($fp, $strip = false)
{
$s = '';
while (true) {
if (fseek($fp, -2, SEEK_CUR) === -1) {
if (!empty($s)) break;
return false;
}
if (($c = fgetc($fp)) === PHP_EOL) break;
$s = $c . $s;
}
if (!$strip) $s .= PHP_EOL;
return $s;
}
$file = '/path/to/your/file.txt';
$src = rfopen($file, 'rb');
$tgt = fopen("$file.rev", 'w');
while ($line = rfgets($src)) {
fwrite($tgt, $line);
}
fclose($src);
fclose($tgt);
// rename("$file.rev", $file);
Replace '/path/to/your/file.txt' with the path to your file. Uncomment the last line to overwrite your file.
精彩评论