Search code examples
phphtmlcoding-style

How to improve readability of HTML code embeded in PHP


Suppose we have something like this:

<?php
while(some statement here)
{
    echo "some HTML here";
    //..................
}
?>

As you know we can do it like this :

<?php
while(some statement here)
{?>
    some HTML here
    ..............
<?php
} ?>

Now,What if I have something like this?

<?php
function example(){
    $out="";
    while(some statement here)
    {
        $out.="some HTML here";
        $out.="some other HTML here";
        //.......................
    }
    return $out;
}
?>

How can I get the HTML code out of <?php ?> so it'll be more readable and can be edited easily using an editor like NotePad++ ? Thanks in advance


Solution

  • So if you want better syntax highlighting you need to close the php tags. Output buffering is a clean way to do this and it lets you maintain syntax highlighting in notepad ++. http://php.net/manual/en/book.outcontrol.php

    <?php
    function example(){
        $foo = "Hello Again";
        ob_start();
        while(some statement here)
        {
            ?>
            <div id="somediv">Hello!</div>
            <div id="somephpvar"><?php echo $foo;?></div>
            <?php 
        }
        return ob_get_clean();
    }
    ?>