PHP 代碼必須包裹在標籤中,Web 伺服器會解析執行 PHP 部分,其餘原樣輸出 HTML。
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
<?= $variable ?> <!-- 等同 -->
<? $var = 'value'; ?>
注意:PHP 7.4+ 棄用短標籤,PHP 8.0 移除。建議統一使用標準標籤。
<ul>
<?php for ($i = 1; $i <= 5; $i++): ?>
<li>Item No <?php echo $i; ?></li>
<?php endfor; ?>
</ul>
輸出:
Item No 1 Item No 2 Item No 3 Item No 4 Item No 5
<?php if ($user->isLoggedIn()): ?>
<div class="welcome">
歡迎,<?= htmlspecialchars($user->name) ?>!
</div>
<?php else: ?>
<a href="/login">登入</a>
<?php endif; ?>
<?php
ob_start();
?>
<div class="widget">
<h3><?= $title ?></h3>
<p><?= $content ?></p>
</div>
<?php
$html = ob_get_clean();
// 現在 $html 可傳遞給佈局、快取或進一步處理
<?php
class Template {
protected $vars = array();
protected $templateDir;
public function __construct($templateDir) {
$this->templateDir = $templateDir;
}
public function assign($key, $value) {
$this->vars[$key] = $value;
}
public function render($template) {
extract($this->vars);
$file = $this->templateDir . '/' . $template . '.php';
if (!file_exists($file)) {
throw new Exception("Template not found: $file");
}
ob_start();
include $file;
return ob_get_clean();
}
}
// 使用
$tpl = new Template(__DIR__ . '/templates');
$tpl->assign('title', '文章標題');
$tpl->assign('articles', $articles);
echo $tpl->render('home');
<!DOCTYPE html>
<html>
<head><title><?= htmlspecialchars($title) ?></title></head>
<body>
<h1><?= htmlspecialchars($title) ?></h1>
<ul>
<?php foreach ($articles as $art): ?>
<li><a href="/article/<?= $art['id'] ?>"><?= htmlspecialchars($art['title']) ?></a></li>
<?php endforeach; ?>
</ul>
</body>
</html>
htmlspecialchars($var, ENT_QUOTES, 'UTF-8') 防 XSS<?= $_GET['input'] ?> 直接輸出用戶輸入short_open_tag 避免與 XML 聲明衝突apcu_store/Redis)| 框架 | 模板引擎 | 特點 |
|---|---|---|
| Laravel | Blade | 編譯為 PHP、繼承、組件、自動轉義 |
| Symfony | Twig | 沙箱、繼承、宏、嚴格語法 |
| CodeIgniter 4 | 內建 View | 簡單、原生 PHP、可選解析器 |
| Yii 2 | PHP 模板 | 佈局、區塊、小部件 |
掌握 PHP 嵌入 HTML 基礎,是理解現代框架視圖層運作的關鍵。建議專案啟動即引入成熟模板引擎,專注業務邏輯開發。