Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep PHP 'View Source' html output clean [duplicate]

Tags:

html

browser

php

This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating.

<ul>
  <li>nav1</li>
  <li>nav2</li>
  <li>nav3</li>
</ul>

Becomes:

<ul>
  <?php foreach($navitems as $nav):?>
  <li><?=$nav?></li>
  <?php endforeach; ?>
</ul>

When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?

like image 278
kevzettler Avatar asked Jun 04 '09 05:06

kevzettler


2 Answers

That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for output buffering havoc when you encounter your first PHP error with output buffering on):

ob_start('ob_tidyhandler');
like image 200
soulmerge Avatar answered Oct 18 '22 02:10

soulmerge


You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as Smarty. Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.

like image 39
Marquis Wang Avatar answered Oct 18 '22 03:10

Marquis Wang