How to style PHP output?

How should I structure PHP files to output nicely formatted HTML?

  • If I generate readable PHP code with the conventional indentation of loops and control structures, the resulting HTML output is FULL of insane whitespace. What's the best practice for PHP to ensure this doesn't happen?

  • Answer:

    Start by putting <?php on the first line and ?> on the last line. You'll now have to either explicitly 'echo' the HTML to the screen,  or close PHP ( ?> ) before your HTML, and then reopen it after. Here's a rough example: <?php //This is my PHP application //The whitepace above won't go to the browser //START awesome conditional code. $helloWorld = 'Hello World'; //END awesome conditional code. ?><!DOCTYPE html><?php //DO NOT LET ANY WHITESPACE APPEAR BEFORE THE DOCTYPE OR THINGS WILL BREAK! ?><html> <head><title>Hello Wild World</title></head> <!-- The whitespace above and below WILL appear in the browser --> <body> <p> Sometimes I just like to shout: "<?php echo ($helloWorld) ?>." </p> And sometimes i like to whisper: " <?php echo ($helloWorld); ?> And sometimes .... <?php echo ('I feel fancy and feel like singing"' . $helloWorld . '."'); ?> </body> </html><?php //This is the end... ?> And there are a dozen other ways to do this. Just remember: what happens in PHP, stays in PHP.

Curtis Oden at Quora Visit the source

Was this solution helpful to you?

Other answers

Division of code into templates/views containing html code and q little of php or templating engine elements and logic code in separate files is a way to go.

Zbyszek Matuszewski

The obvious answer would be to use templates, however that will not help with making your html output perfectly indented. 1) i think you should not worry about indentation of output html. actually every white space should be ommited as its just extra charracters client needs to download. when you need to read your html output pretty much every editor will automaticly indent it for you. 2) if you really want to have your output perfectly indented you could send your output to php.tidy ...  http://php.net/manual/en/tidy.examples.basic.php it should get you just what you want and i think the example is super clear.

Peter Pišljar

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.