...

View Full Version : Problems with embedded PHP



clarinetmeister
06-21-2010, 11:11 PM
I wrote the following code for my website to read a txt file with news posts and write them to the web page. Each line of the text file is formatted date, time|username|posttitle|postbody. The script splits the text file into an array by line, and then reads each element of the array. It is embedded into the html file, which uses CSS. The final result is supposed to look something like the lower post in this screenshot:

http://dl.dropbox.com/u/3771473/screenshot.jpg

but instead comes out like the upper post in the screenshot. Have I made a syntax error somewhere or something?


<?php
$myFile = "posts.txt";
$lines = file($myFile);
foreach ($lines as &$ln):
echo $ln;
$data = explode ("|", $ln);
?>
<div class='post'><a name='NewMsg'></a><h1><? echo $data[2] ?></h1><p>Posted by: <? echo $data[1] ?></p><p><? echo $data[3] ?></p><p class='post-footer align-right'><a href='index.html' class='readmore'>Read more</a><span class='date'><? echo $data[0] ?></span></p>
<?
endforeach;
?>

Thanks

mlseim
06-22-2010, 03:05 PM
You must have a blank line or two in your .txt file and it's printing those also.
If a variable is empty, it must be a blank line, so don't print it.

Try this:



<?php
$myFile = "posts.txt";
$lines = file($myFile);
foreach ($lines as &$ln){
$data = explode ("|", $ln);
if($data[0]){
echo"
<div class='post'><a name='NewMsg'></a><h1>".$data[2]."</h1><p>Posted by:".$data[1]."</p><p>".$data[3]."</p><p class='post-footer align-right'><a href='index.html' class='readmore'>Read more</a><span class='date'>".$data[0]."</span></p>
";
}
}
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum