如何提高嵌入 PHP 中的 HTML 代码的可读性

How to improve readability of HTML code embeded in PHP

假设我们有这样的事情:

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

如您所知,我们可以这样做:

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

现在,如果我有这样的事情怎么办?

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

如何从 <?php ?> 中获取 HTML 代码,以便它更具可读性,并且可以使用像 NotePad++ 这样的编辑器轻松编辑?提前致谢

所以如果你想要更好的语法高亮,你需要关闭 php 标签。输出缓冲是一种干净的方式来做到这一点,它可以让你在记事本++中保持语法高亮。 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();
}
?>

简答:使用输出缓冲区控制(http://php.net/manual/en/book.outcontrol.php)

例子

<?php

function example(){
    ob_start();

    $i = 0;
    while($i < 10)
    {
        ?>
        Hello<br/>
        <?php
        $i++;
    }

    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}


echo example();

长答案:你会想要使用像 Twig (https://twig.sensiolabs.org/) 这样的模板引擎来完全在 PHP 代码之外拥有 HTML(当然还有更多的好处)

如果你想自己写函数,最好的方法是使用output buffering control,例如:

<?php
function() {
    ob_start();
    ?>
     <h1>Hello world</h1>
    <?php
    return ob_get_clean();
}

不过,强烈建议您使用模板库,例如mustache. Most PHP frameworks include their own template mechanism; have a look at laravel, and cakePHP