开发者

Is there a better way to write HTML strings in PHP?

开发者 https://www.devze.com 2023-01-31 15:28 出处:网络
I find myself writing a lot of functions in PHP that return HTML code. They may look something like this:

I find myself writing a lot of functions in PHP that return HTML code. They may look something like this:

function html_site_head()
{
    return
        "
            <div id=\"site_header\">
                <div id=\"site_header_inner\">
                    <div id=\"site_header_logo\"></div>

                    <div id=\"site_header_countdown\">BARE XX DAGER IGJEN</div>
                </div>
            </div>
        ";
}

Now I can swear I've seen better ways to write long strings in PHP. I like python's way of doing it:

return """
    <div id="site_header">
        <div id="site_header_inner">
            <div id="site_header_logo"></div>

            <div id="site_header_countdown">BARE XX DAGER IGJEN</div>
        </div>
    </div>
"""

As you don't have to escape quot开发者_如何学Goation marks. An alternative is using single quotation marks, but that means no using PHP variables directly in the string. I swear I've seen something like this in PHP:

return <<<
    <div id="site_header">
        <div id="site_header_inner">
            <div id="site_header_logo"></div>

            <div id="site_header_countdown">BARE XX DAGER IGJEN</div>
        </div>
    </div>

Or something similar. Could someone refresh my memory on this?

Thanks


PHP knows several kinds of syntax to declare a string:

  • single quoted

    ' … '
    
  • double quoted

    " … "
    
  • heredoc syntax

    <<<DELIMITER
     …
    DELIMITER
    
  • nowdoc syntax (since PHP 5.3.0)

    <<<'DELIMITER'
     …
    DELIMITER
    

So you don’t have to use the double quotes per se.


If you need a method that can be used to store HTML into a string, this is the way to do it.

I would not use any of these other suggested methods lol, I would use an Output buffer. These other methods all seem mega dirty (because at scale there would be a lot of special characters flying around)... so at the risk of offending someone i'll just say the reasons why I like my way.

If you use an output buffer like I have done...

When using an IDE you can still have great intelisense help with HTML and PHP separate from one another and still code out generic DOM Objects quickly.

When viewing the code it looks a lot more human readable.

The HTML code can be passed in its DOM ready state rather than as a string which will eventually need to be parsed and eventually created into a DOM ready state.

When using HTML as a string method it can get really rough trying to use the various string function search and replace methods in order to change some of your code after runtime. For example looking for the <img> tag within a massive string of other HTML elements can be daunting especially when trying to find stuff between tags...

I would use the Output Buffer Stream like so...

ob_start();
?>
    <div id="site_header">
        <div id="site_header_inner">
            <div id="site_header_logo"><?php echo $PhpVar; ?></div>
            <div id="site_header_countdown">BARE XX DAGER IGJEN</div>
        </div>
    </div>
<?php
$output = ob_get_clean();
ob_flush();

return $output; OR return echo $output


Better way - don't write spaghetti code, use template or

// php code
?>
<div id="site_header">
    <div id="site_header_inner">
        <div id="site_header_logo"><?=$echoPhpVar?></div>
        <div id="site_header_countdown">BARE XX DAGER IGJEN</div>
    </div>
</div>
<?php
//php code


You can use a HEREDOC:

<?php

function blah() {
  $bar = <<<EOS
  <div id="site_header">
        <div id="site_header_inner">
            <div id="site_header_logo"></div>

            <div id="site_header_countdown">BARE XX DAGER IGJEN</div>
        </div>
  </div>
EOS;

return $bar;
}

?>


What you're looking for is heredoc syntax or nowdoc syntax.


Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate":

<?php
function removeslashes($string)
{
    $string=implode("",explode("\\",$string));
    return stripslashes(trim($string));
}

/* Example */

$text="My dog don\\\\\\\\\\\\\\\\'t like the postman!";
echo removeslashes($text);
?>

RESULT: My dog don't like the postman!

This flick has served me very well, because I had this problem before.

Source: here


As Haim said - heredocs are the way to go.

If you find yourself writing single lines, remember (or realise) that you can use single quotes for HTML attributes (don't believe anyone that tries to tell you they aren't valid).

So, e.g.:

$html = "<div id='blah'>$contents</div>";


I like to suggest this PHP library that can handle generating just about any HTML tag with php and uses closure nesting which helps readability as well.

https://github.com/raftalks/Form

for example - a table inside a div tag

Html::make('div', function($html))
{
    $html->table(function($table)
    {
        $table->thead(function($table)
        {
            $table->tr(function($tr)
            {
                $tr->th('item');
                $tr->th('category');
            });
        });


        $table->tr(function($tr)
        {   
            $tr->td()->ng_bind('item.name','ng-bind');
            $tr->td()->ng_bind('item.category','ng-bind');

            $tr->setNgRepeat('item in list','ng-repeat'); //using second parameter to force the attribute name.
        });

        $table->setClass('table');
    });

   $html->setClass('tableContainer');
});
0

精彩评论

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