Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problems with embedded PHP

    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?

    Code:
    <?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

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,549
    Thanks
    8
    Thanked 1,095 Times in 1,086 Posts
    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 Code:
    <?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>
    "
    ;
       }
    }
    ?>


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •