skip to Main Content

I write my HTML code in PHP syntax and need to save HTML indent

i use ‍‍‍‍{ … } for this job.

I’m afraid that is not the right way to save indentation

And it may not be supported in the next version or it may cause an error somewhere

Although I have never seen a problem

<?php 
$html = '';

$html .= '<div class="a">';
{
    $html .= '<div class="b">';
    {
        $html .= '<div class="c">';
        {
            $html .= 'Hello world';
        }
        $html .= '</div>';
    }
    $html .= '</div>';
}
$html .= '</div>';

echo $html;
?>

Can i use this way to save HTML indent?

3

Answers


  1. Here is your example with PHP heredocs. You can read about them here in the official documentation.

    Example:

    <?php
        
    $html = <<<END
    <div class="a">
        <div class="b">
            <div class="c">
                Hello world
            </div>
        </div>
    </div>
    END;
      
    echo $html;
    

    Result:

    <div class="a">
        <div class="b">
            <div class="c">
                Hello world
            </div>
        </div>
    </div>
    
    Login or Signup to reply.
  2. There’s no problem using curly braces. In PHP they are useful when having if, while etc. But I suggest two following formats that make your code more readable.

    1st: In this format, intents will include in the HTML file.

    $html = 
    '<div class="a">
        <div class="b">
            <div class="c">
                Hello world
            </div>
        </div>
    </div>';
    

    2nd: In this format, intents are only in PHP file.

    $html = 
    '<div class="a">' .
        '<div class="b">' .
            '<div class="c">' .
                'Hello world' .
            '</div>' .
        '</div>' .
    '</div>';
    
    Login or Signup to reply.
  3. It’s better to store html templates separately

    <div class="a">
        <div class="b">
            <div class="c">
                <?php echo $text ?>
            </div>
       </div>
    </div>
    

    This example will output HTML with text "Hello world":

    <?php
    $text = 'Hello world';
    include 'template.php';
    

    You can also store generated html to variable using output buffering:

    <?php 
    $text = 'Hello world';
    ob_start();
    include 'template.php';
    $html = ob_get_clean();
    

    If you not want to use include, you can remember that php is essentially a template engine and write something like that:

    <?php
    $text = 'Hello world';
    //ob_start();
    ?>
    <div class="a">
        <div class="b">
            <div class="c">
                <?php echo $text ?>
            </div>
       </div>
    </div>
    <?php
    // $html = ob_get_clean();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search