【问题标题】:How to improve readability of HTML code embeded in PHP如何提高 PHP 中嵌入的 HTML 代码的可读性
【发布时间】:2017-06-30 10:35:03
【问题描述】:

假设我们有这样的事情:

<?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;
}
?>

如何从&lt;?php ?&gt; 中获取 HTML 代码,使其更具可读性并且可以使用 NotePad++ 等编辑器轻松编辑?提前致谢

【问题讨论】:

    标签: php html coding-style


    【解决方案1】:

    所以如果你想要更好的语法高亮,你需要关闭 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();
    }
    ?>
    

    【讨论】:

    【解决方案2】:

    简答:使用输出缓冲区控制 (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(当然还有更多好处)

    【讨论】:

      【解决方案3】:

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

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

      但是,强烈建议您使用模板库,例如mustache。大多数 PHP 框架都包含自己的模板机制;看看laravelcakePHP

      【讨论】:

      • 你的意思是 ob_start() 和 ob_get_clean() 。正确的?因为我没有找到任何名为 obp_start() 或 obp_get_clean() 的函数
      猜你喜欢
      • 2017-08-22
      • 1970-01-01
      • 2010-10-07
      • 2015-05-04
      • 2020-11-18
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      相关资源
      最近更新 更多