Home > Blockchain >  Can i use {} in PHP for save my HTML indent
Can i use {} in PHP for save my HTML indent

Time:12-26

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 >';
{
    $html .= '<div >';
    {
        $html .= '<div >';
        {
            $html .= 'Hello world';
        }
        $html .= '</div>';
    }
    $html .= '</div>';
}
$html .= '</div>';

echo $html;
?>

Can i use this way to save HTML indent?

CodePudding user response:

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 >
    <div >
        <div >
            Hello world
        </div>
    </div>
</div>';

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

$html = 
'<div >' .
    '<div >' .
        '<div >' .
            'Hello world' .
        '</div>' .
    '</div>' .
'</div>';

CodePudding user response:

It's better to store html templates separately

<div >
    <div >
        <div >
            <?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 >
    <div >
        <div >
            <?php echo $text ?>
        </div>
   </div>
</div>
<?php
// $html = ob_get_clean();

CodePudding user response:

Here is your example with PHP heredocs. You can read about them here in the enter image description here

  • Related