Includes make code look messy

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Hendeca
Forum Commoner
Posts: 29
Joined: Tue Nov 18, 2008 1:27 pm

Includes make code look messy

Post by Hendeca »

Hello,

I've been having a problem using includes. I use repeated code in my includes for things like navigation bars that will appear on every page. However, when I look at the resulting source code on the website using the include, the code from the include always looks very messy and loses its nesting and indentation. How can I fix this? Here's an example from my portfolio site:

http://www.hendeca.com/web.php

This site uses the following include:

Code: Select all

 
<?php
$currentPage = basename($_SERVER['SCRIPT_NAME'], '.php');
$brianmatch = '/brianmeehl/';
$fouredgematch = '/fouredge/';
$transmatch = '/transparencyfight/';
$connormatch = '/chooseconnor/';
?>
    <ul id="weblist">
        <?php if(!preg_match($connormatch, $currentPage)) {?><li><a href="web.chooseconnor.php">Choose Connor.com</a></li><?php } else {?> <li class="current">Choose Connor.com</li> <?php } ?>
 
        <?php if(!preg_match($brianmatch, $currentPage)) {?><li><a href="web.brianmeehl.php">Brian Meehl.com</a></li><?php } else {?> <li class="current">Brian Meehl.com</li> <?php } ?>
 
        <?php if(!preg_match($fouredgematch, $currentPage)) { ?><li><a href="web.fouredge.php">The Four Edge.com</a></li><?php } else {?> <li class="current">The Four Edge.com</li> <?php } ?>
 
        <?php if(!preg_match($transmatch, $currentPage)) {?><li><a href="web.transparencyfight.php">Transparency Fight.com</a></li><?php } else {?> <li class="current">Transparency Fight.com</li> <?php }?>
    </ul>
 
But if you look at the source code for web.php you'll see that the indentation is all out of whack. Any idea why? I've tried messing around with spacing, indentation, and the like but haven't been able to get it to work yet. Thanks,

-Neal
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Includes make code look messy

Post by Eran »

You need to output the link-break character (\n) at the end of lines for line-breaks to show in the source. Make sure you output it between double-quotes:

Code: Select all

echo "\n"; //not echo '\n';
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Includes make code look messy

Post by requinix »

PHP has a habit of dropping whitespace after the closing ?>. "Whitespace" includes newlines, so if you put the ?> at the end of a line then the next one gets stuck onto the end.

Either echo a \n manually or put a space after each ?> (so the space gets ignored and the newline stays intact).
Post Reply