在 HTML 中编写 PHP 的更好方法?

我想知道是否有更好的方法在 HTML 中输出此代码,其中包括 PHP 变量来构建导航栏菜单。


<ul>

   <?php

     echo "<li><a href='$a->url'>$a->title</a>";

        echo "<ul class='submenu'>";

           echo "<li><a href='$w->url'>$w->title</li>";

           echo "<li><a href='$b->url'>$b->title</li>";

           echo "<li><a href='$c->url'>$c->title</a></li>";

           echo "<li><a href='$d->url'>$d->title</a></li>";

        echo "</ul>";

    echo "</li>";

   ?>

</ul>


拉丁的传说
浏览 108回答 2
2回答

一只萌萌小番薯

尽管性能上几乎没有差异,但您应该始终尝试将 HTML 和 PHP 分开。这会导致代码更加简洁,更容易阅读。<ul>&nbsp; &nbsp; <li><a href='<?= $a->url;?>'><?= $a->title; ?></a>&nbsp; &nbsp; &nbsp; &nbsp;<ul class='submenu'>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href='<?= $w->url;?>'>$w->title</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href='<?= $b->url; ?>'>$b->title</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href='<?=$c->url; ?>'>$c->title</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href='<?= $d->url?>'>$d->title</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp;</ul>&nbsp; &nbsp;</li></ul>这里的另一个好处是:您可以从 IDE 中突出显示 HTML 中的语法错误。您错过了关闭几个<a>- 标签

米琪卡哇伊

<ul>&nbsp; <li><a href='<?php echo $a->url; ?>'><?php echo $a->title; ?></a>&nbsp; &nbsp; <ul class='submenu'>&nbsp; &nbsp; &nbsp; <li><a href='<?php echo $w->url; ?>'><?php echo $w->title; ?></a></li>&nbsp; &nbsp; &nbsp; <li><a href='<?php echo $b->url; ?>'><?php echo $b->title; ?></a></li>&nbsp; &nbsp; &nbsp; <li><a href='<?php echo $c->url; ?>'><?php echo $c->title; ?></a></li>&nbsp; &nbsp; &nbsp; <li><a href='<?php echo $d->url; ?>'><?php echo $d->title; ?></a></li>&nbsp; &nbsp; </ul>&nbsp; </li></ul>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5