Reversing the contents of a file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Teck
Forum Newbie
Posts: 5
Joined: Wed Sep 19, 2007 2:01 pm

Reversing the contents of a file?

Post by Teck »

Hello everyone,

I'm having trouble reversing the order of the contents of a file, basically I want to read the files contents in a descending order.

My code:

Code: Select all

 
<?php
// --- 
$today = date('Y/m/d');
 
//open the file to pull information
$file  = 'TR1.1';
$fd = fopen($file, "r") ;
$content = fread($fd, filesize($file));
    fclose($fd);
 
// Delimiters for sorting the code
$delimiter = "\n";
$delimiter2 = ",";
 
// create the array from the contents of the file
$split = explode($delimiter, $content);
$flip = array_reverse($split);
// read the first line of the reversed contents and break it down into variables
$rerun = explode($delimiter2, $flip['0']);
 
  $display .= "
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['1']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['2']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['3']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['4']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['5']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['6']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['7']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['8']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['9']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['10']."</td>
    <td align='center' valign='middle' bgcolor='#FFFFFF'>".$rerun['11']."</td>
  ";
 
 
?>
 
My Results are:

Code: Select all

 
1,08/07/22,20:03:58,3.6,263,8.4,3.9,32.4,13.1,908.2,14,2.4,
Array
 
It's not reversing the contents of the file. The line 1,08/07/22,20:03:58,3.6,263,8.4,3.9,32.4,13.1,908.2,14,2.4, is the first entry in the file but it should be different.

The second line Array should display the information in between the commas on the first line.


Thanks
WebbieDave
Forum Contributor
Posts: 213
Joined: Sun Jul 15, 2007 7:07 am

Re: Reversing the contents of a file?

Post by WebbieDave »

What about:

Code: Select all

$contents = file_get_contents('myfile.txt');
$reversedContents = strrev($contents);
Post Reply