我创建了许多需要php,html和css的网站。他们都工作正常,但我现在正在考虑是否所有的时间我以错误的方式做到这一点。 通常,首先我构建网站模板和样式,然后我编码PHP。 然后我只是在HTML中包含php函数等。 例如,看一下列出一些帖子的表(index.php):
<div class="posts">
<h1 class="content-title">New Posts</h1>
<?php
$rows = list_posts();
while ($row=mysql_fetch_array($rows)) {
echo "
<div>
<img class='post-avatar' src='img/icon_newsletter.jpg'>
<h2 class='post-title'>".$row['post_title']."</h2>
<p class='post-meta'>
Από <a href='#'>".$row['post_user']."</a> | ".$row['post_date']." | <a class='post-views' href='viewpost.php?id=".$row['post_id']."#comments'>Comments: ".total_comments($row['post_id'])."</a>
</p>
<p>
".substr($row['post_body'], 0, 180)."...
</p>
<img class='post-icon-read' src='img/read.png' /> <a href='viewpost.php?id=".$row['post_id']."'>Συνέχεια άρθρου..</a>
</div>
";
}
?>
</div>
答案 0 :(得分:0)
还有改进的空间。
将HTML保留在PHP中。它不是个人意见,有技术原因。
执行此操作时:
html
<?php PHP ?>
html
<?php ?>
html
<?php PHP ?>
html
当您在HTML模式和PHP模式之间来回切换时,PHP中存在开销。它让你看起来像Word Press Hack。
一些事情: - Heredoc语法 - 数字阵列 - 逃避报价
从基本模板开始:
echo <<<EOT
// Top of page
EOT;
while ($row=mysql_fetch_array($rows), MYSQL_NUM) {
}
echo <<<EOT
// bottom of page
EOT;
使用MYSQL_NUM
的原因是列值可以在没有连接的情况下使用。
而不是
<a href='#'>".$row['post_user']."</a> | ".$row['post_date']." | <a class='post-views' href='viewpost.php?id=".$row['post_id']."#comments'>Comments: ".total_comments($row['post_id'])."</a>
你可以这样做:
$comment = total_comments($row[2]) ;
echo "<a href=\"#\">$row[0]</a>$row[1]<a class=\"post-views\" href=\"viewpost.php?id=$row[2]#comments\">Comments: $comment</a>";
反斜杠将在双引号内转义双引号。引号不需要在Heredoc中转义。
单维数字数组可以在双引号内和Heredoc中使用。
返回页首:
echo <<<EOT
<!DOCTYPE html>
<html lang="en"><head><title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Edit Rotation Diet</title>
<style type="text/css">
</style></head>
<body><div id="page">
EOT;
页面底部:
echo <<<EOT
<script type="text/javascript">//<![CDATA[
//]]>
</script></body></html>
EOT;
假设页面内容是一个表格
<body><div id="page"><table>
EOT;
while ($row=mysql_fetch_array($rows), MYSQL_NUM) {
echo <<<EOT
<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
</tr>
EOT;
}
echo <<<EOT
</table>
<script type="text/javascript">//<![CDATA[
HTML与PHP的缩进是错误的。您应该考虑当有人查看源时HTML的外观。在大多数Word Press页面上查看来源..看起来像垃圾。
echo和第一个html之间的空白行为您提供换行符。
当你像你一样回复HTML时,当你查看源代码时,它看起来真的很糟糕,比如Word Press。
就个人而言,我不喜欢四个空格缩进。在您知道它之前,您的代码隐藏在右边界之外。我用两个空格。
我认为这很丑陋,浪费了垂直空间:
if($x = 1)
{
echo '<p>one</p>';
}
else
}
echo '<p>two</p>'
}
我认为这很清楚。没有过多的垂直滚动/
if($x = 1){
echo '<p>one</p>';
}
else{
echo '<p>two</p>
}