且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将HTML转换为PHP或使用Echo?哪个更好?

更新时间:2023-02-23 11:34:43

当然,这会随着每种情况而变化。如果你正在做整个页面,并且有很大的部分没有任何PHP,那么我会跳出PHP并且只写纯HTML,而如果有一个部分有很多PHP变量,我会在PHP中完成。

It's all about which you find the most readable. Of course, this will vary with each situation. If you were doing an entire page, and there were large sections which did not have any PHP in it, then I'd break out of PHP and just write the plain HTML, whereas if there was a section which had a lot of PHP variables, I'd do it all in PHP.

例如:

For example:

<table>
    <tr>
        <td colspan="<?php echo $numCols; ?>">
            <?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
        </td>
    </tr>
</table>

与:

versus:

<?php
echo "<table>"
    . "<tr>"
    .    "<td colspan=\"" . $numCols . "\">"
    .        $a . ", " . $b . " and " . $c
    .    "</td>"
    . "</tr>"
    . "</table>"
; ?>



Or

<?php
echo "<table>
         <tr>
            <td colspan='{$numCols}'>
               {$a}, {$b}, and {$c}
            </td>
         </tr>
      </table>";
?>

另外不要忘记 printf

<?php
printf("<table>"
    . "<tr>"
    .    "<td colspan=\"%d\">%s, %s and %s</td>"
    . "</tr>"
    . "</table>"
    , $numCols
    , $a
    , $b
    , $c
);
?>