I am successfully reading and displaying a .txt file with 3 variables, lets say for example name, age and comments.

When the file is written, 1 name, 1 age and 1 comment gets written on a line. Any further additions get added as a new line.

When this gets read in my php page, it displays the info but all on the same line.

I really want to have an image box with name and age underneath and then comments to the right hand side. Also, added css to have comments in speech marks (which would be a small image) would be perfect.

Any help?

This code reads and displays the file:

$myFile = "location.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
echo $theData;

7 Years
Discussion Span
Last Post by Excizted

You could separate your fields with a comma or some other unique character (when the file is written) and then use explode when you read the line to separate the fields.


Yes, it is common to have that kind of files looking like this

Peter;26;This guy is awesome!


Peter,26,This guy is awesome!

or you could specify multilined sections like this, but your need doesn't seem like this is any better unless you of course like the syntax.

This guy is awesome!

ah, awesome. Cheers guys. That's very useful and so simple! I can't believe I couldn't find how to do that on google!

Only, I'm now having problems displaying more than 1 line.

I'm gussing i need some sort of loop in place, working on it now but any help would be appreciated

Edited by ptemedia: n/a


Can't edit above post :(

Here is my code so far, it works, but obviously only returns 1 line of the text file. Each line contains 1 name, 1 age and 1 comment:

$myFile = "textfile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$messages = explode(";", $theData);

Name: <?php echo "$messages[0]"?><br />
Age: <?php echo "$messages[1]"?><br />
Message: <?php echo "$messages[2]"?><br />


I have worked it out and posted it here for anyone else who stumbles across this thread and needs answers:

$myFile = "mytextfile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$messages = explode("\n", $theData);
    foreach ($messages as $individual){
        $individual = explode(";", $individual);
        echo "<p>Name: $individual[0]<br />";
        echo "Age: $individual[1]<br />";
        echo "Message: $individual[2]<br /></p>";

Many Thanks anyway, Patrick Taylor-Edwards

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.