Forum Moderators: coopster
I have a text file with information such as
Number of Posts ¦ 23
Users Logged in ¦ 12
I know this kind of thing is usually in a database but was hoping to get the information from a text file to begin with.
What I want is a way of getting the information from the text file (especially the data after the ¦ ) and displaying it in a table, but its causing me some problems.
Is this possible?
Could anyone give me some help/advise as to how to get it to work.
Would it be easier to set up a small database and use that? If I was to do that what would be the best way to go about it?
Thanks
P.S I've just started learning how PHP works sorry if this seems like a stupid problem.
There are a number of ways to accomplish your task. Along with the offering here by justageek, you may also want to read Basics of extracting data from CSV files [webmasterworld.com] in the PHP Forum Library [webmasterworld.com].
This is what I have at the moment
<?php
$fp = fopen("test.txt","r");
$line_data = file("test.txt");
for($i=0;$i<=count($line_data);$i++){
$line_elements = explode("¦",$line_data);
$posts = trim($line_elements[0]);
$logged_in_users = trim($line_elements[1]);
}
fclose($fp);
print("$posts");
print("$logged_in_users");
?>
But when I try to view it it just displays the word Array on the screen.
But I can't see why it does this.
print '<pre>';
print_r($posts);
print_r($logged_in_users);
print '</pre>';
First, you are going to want to print your statements inside the loop, so you could trim a bit of code by just printing the trimmed value rather than storing it in a variable.
Secondly, the loop should only be occurring when the index is less than the array count as arrays begin with 0, but the total count will always be one more.
And lastly, we need to use an index in the array assignment within the explode function:
$fp = fopen("test.txt", "r");
$line_data = file("test.txt");
for($i=0;$i<count($line_data);$i++){
$line_elements = explode("¦", $line_data[$i]);
print trim($line_elements[0]) . '<br />';
print trim($line_elements[1]) . '<br />';
}
fclose($fp);
Absolutely, that's the beauty of it all! See where I inserted HTML <br /> tags? Replace those with your <td> and you are good to go. Instead of printing the information during the loop, you can build a variable and print it later. Something like this:
<?php
$table_data = '';
$fp = fopen("test.txt", "r");
$line_data = file("test.txt");
for($i=0;$i<count($line_data);$i++){
$line_elements = explode("¦", $line_data[$i]);
$table_data .= '<tr><td>' . trim($line_elements[0]) . '</td>';
$table_data .= '<td>' . trim($line_elements[1]) . '</td></tr>';
}
fclose($fp);
?>
<html><head><title>Title</title></head><body>
<table><?php print $table_data; ?></table>
</body></html>