开发者

Php formatting output html

开发者 https://www.devze.com 2023-02-28 16:44 出处:网络
In ruby on Rails, you have the option to create cleaner and well formated output: <div> <%= 3.times do -%>

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 thin开发者_JS百科g 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?


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


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.


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;
}


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 ;)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消