Using 'list' to list out variables from .txt 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
implications
Forum Commoner
Posts: 25
Joined: Thu Apr 07, 2011 3:59 am

Using 'list' to list out variables from .txt file

Post by implications »

So I have created a flatfile script where I store text data into a .txt file-format database instead of using MySQL. I'm planning on listing out the contents of that .txt file, which is formatted to appear like so:

1\¦Lines of text here\¦IP address\¦
2\¦Lines of text here\¦IP address\¦

The first 'segment' is the ID, as in the numerical order of the text stored. The second part is where the text information is submitted via user input and then stored into the .txt database. The third part is the user's IP address.

So then my list function goes something like this:

Code: Select all

list($id, $data, $ip) = getRow(DATABASE)
It lists out the information from my .txt file (DATABASE) using this function:

Code: Select all

function getRow($file) {
	$fd = fopen($file, "r") or die("Can not open file: $file");
	$rstr = fread($fd, filesize($file));
	fclose($fd);
	return explode("\¦", $rstr);
}
Now the list and function thing works fine because I'm able to echo out individual 'segments' separately. Say if I want to echo out the user submitted data, then I just go

Code: Select all

<?php echo $data ?>
and the corrrect info appears. But then the problem is, I can't echo out every single line in the database. If I do the echo data thing, I can only echo out the data from the first row (ID no.1). This probably has something to do with the way the function is coded but I'm not that familiar with PHP yet so I don't know how to tweak so it can echo out the data from every single row.

Does anyone know what I can modify to make it work?
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Using 'list' to list out variables from .txt file

Post by tr0gd0rr »

Your getRow() function opens a file, reads the first row, closes the file and returns the data in the first row. You need to visit all the rows. Try this pattern: get the entire file contents, split the file into lines, read each line. Here is an example:

Code: Select all

$entireFile = file_get_contents($file);
$lines = explode("\n", $entireFile);
foreach ($lines as $line) {
  list($id, $data, $ip) = explode("\|", $line);
  echo "$data<br>";
}
implications
Forum Commoner
Posts: 25
Joined: Thu Apr 07, 2011 3:59 am

Re: Using 'list' to list out variables from .txt file

Post by implications »

That did the trick. Thanks! :D
Post Reply