Page 1 of 1

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

Posted: Mon May 09, 2011 4:23 am
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?

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

Posted: Mon May 09, 2011 11:50 am
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>";
}

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

Posted: Tue May 10, 2011 5:15 am
by implications
That did the trick. Thanks! :D