Ibu
Ibu

Reputation: 43810

Php formatting output html

In ruby on Rails, you have the option to create cleaner and well formated output:

<div>
      <%= 3.times do -%>
      <%= "Hello World" -%>
      <%= end -%>
</div>

and the output will be:

<div>
   Hello World
   Hello World
   Hello World
</div>

But when i do the same thing in php:

    <div>
          <?php for ($i =0; $ < 3;$i++): ?>
          <?php echo "Hello World" ?>
          <?php endfor; ?>
    </div>

I get something like this:

<div>       Hello World
 Hello World
       Hello World
    </div>

is there something like rubys "-%>" in php that help me acheive the same thing?

Upvotes: 4

Views: 400

Answers (5)

heath
heath

Reputation: 107

I will occasionally do something like the following:

<?php
echo "<html>";
echo "   <head>";
echo "   </head>";
echo "   <body>";
echo "       <div>";
echo "           $variable";
echo "       </div>";
echo "   </body>";
echo "</html>";
?>

Where all the lines are indented in the text so the HTML is easier to read. However, this only really makes sense to do if you have a lot of variables to add to your HTML. As someone mentioned earlier, the browser does not rely on indentation to display the page. The only time you would need correct HTML indentation is if you expect someone to look at the page source with their browser.

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

Fixed the code: (looks ugly huh?)

    <div>

<?php for ($i =0; $ < 3;$i++):
echo "\t\tHello World" ?>
endfor; ?>
    </div>

Whitespace inbetween the <?php ?> tags is preserved, maybe Ruby does something fancy to filter it out, PHP in any case does not.

It is always tricky to decide which part you want to print with PHP and which part you want in native HTML. In any case, browsers don't care about whitespace ;)

Upvotes: 1

Aaron W.
Aaron W.

Reputation: 9299

Don't think it's offered. Like @Antwan states, you'd just have to add your own newlines and tabs on your echos. Note: Not sure there is a full proof function to handle this since your IDE will affect your newlines and spacing as well.

function echonice($str) {
    echo "\n\t".$str;
}

Upvotes: 1

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

You can use HTMLTidy which is bundled with PHP.

However, you should consider that processing the markup with Tidy can slow down your site. If you must use Tidy, you should cache the output from it, or only enable it for debugging purposes.

Upvotes: 1

Antwan van Houdt
Antwan van Houdt

Reputation: 6991

Keep in mind that PHP is a preprocessor, so basically it just appends some stuff to your files. This means that to achieve the correct "style" or "cleanness" in your file you will need to add newlines etc. to ( randomly ) generated stuff.

for instance for every loop add \n to the end of the string so it will print it on a new line of the file. If you want a tab you could do \t and so forth

Upvotes: 1

Related Questions