smart reading from a text 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
Monotoko
Forum Commoner
Posts: 64
Joined: Fri Oct 26, 2007 4:24 pm

smart reading from a text file

Post by Monotoko »

Hello there fellow coders, i was wondering if one of you wouldnt mind helping me with this problem i seem to have hit:

There is an application which i am currently coding, which writes everything that is searched for into a file called search.txt, basically, it looks like this:

--
Windows XP, http://www.example.com, 26/10/09, 00:00
Tractors, http://www.example2.com, 29/10/09, 04:12
--

I was wondering how i would go about tabulating raw data such as that in a PHP page? I assume it would have to know the comma's were seperators...
If anyone can think of a better way to do this (it is purely a flat-file system) that would be helpful too

~Monotoko
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: smart reading from a text file

Post by requinix »

A combination of fopen, fgetcsv, and fclose should do the job for you.
Monotoko
Forum Commoner
Posts: 64
Joined: Fri Oct 26, 2007 4:24 pm

Re: smart reading from a text file

Post by Monotoko »

hmmm, would you mind elaborating how i would use fgetcsv for this task?

from what i can see its for .csv files?

(sorry if im missing something very obvious, it is 4am here)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: smart reading from a text file

Post by requinix »

Here's the example from the manual page for fgetcsv. Comments added.

Code: Select all

<?php
$row = 1; // a counter for line numbers
$handle = fopen("test.csv", "r"); // open the test.csv file for reading
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // while there are still lines to read
    // $data is an array with [0]=the first column, [1]=the second column, etc
    // columns are separated by commas
    $num = count($data); // the number of columns
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++; // next row
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n"; // print everything in the row
    }
}
fclose($handle); // close the file
?>
It doesn't have to be a CSV file: any file that has "columns" will work.
Monotoko
Forum Commoner
Posts: 64
Joined: Fri Oct 26, 2007 4:24 pm

Re: smart reading from a text file

Post by Monotoko »

ahha i see, thank you very much :)
Post Reply