Page 1 of 1

Includes make code look messy

Posted: Sun Dec 07, 2008 4:22 pm
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

Re: Includes make code look messy

Posted: Sun Dec 07, 2008 4:44 pm
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';

Re: Includes make code look messy

Posted: Sun Dec 07, 2008 4:57 pm
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).