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;

Recommended Answers

All 6 Replies

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

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

Good job :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.