萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 嵌入 HTML 完整指南:從基礎語法到進階模板模式

基本語法

PHP 代碼必須包裹在標籤中,Web 伺服器會解析執行 PHP 部分,其餘原樣輸出 HTML。

標準標籤(推薦)

<!DOCTYPE html>
<html>
<head>
    <title>PHP Test</title>
</head>
<body>
    <?php echo '<p>Hello World</p>'; ?>
</body>
</html>

短標籤(需啟用 short_open_tag)

<?= $variable ?> <!-- 等同  -->
<? $var = 'value'; ?>

注意:PHP 7.4+ 棄用短標籤,PHP 8.0 移除。建議統一使用標準標籤。

進階嵌入模式

1. 控制結構與 HTML 混合

<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

2. 替代語法(殘留冒號+end關鍵字)

<?php if ($user->isLoggedIn()): ?>
    <div class="welcome">
        歡迎,<?= htmlspecialchars($user->name) ?>!
    </div>
<?php else: ?>
    <a href="/login">登入</a>
<?php endif; ?>

3. 區塊輸出捕獲(Output Buffering)

<?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');

模板文件 templates/home.php

<!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>

安全最佳實踐

  1. 輸出轉義:htmlspecialchars($var, ENT_QUOTES, 'UTF-8') 防 XSS
  2. 嚴禁:<?= $_GET['input'] ?> 直接輸出用戶輸入
  3. 模板引擎(Twig、Blade、Smarty)自動轉義,強烈建議生產環境使用
  4. 關閉 short_open_tag 避免與 XML 聲明衝突

效能優化

  • 啟用 OPcache(生產環境必須)
  • 模板編譯快取(Twig/Blade 自動處理)
  • 避免在模板中執行複雜邏輯/資料庫查詢
  • 大型頁面考慮片段快取(apcu_store/Redis)

現代框架整合

框架模板引擎特點
LaravelBlade編譯為 PHP、繼承、組件、自動轉義
SymfonyTwig沙箱、繼承、宏、嚴格語法
CodeIgniter 4內建 View簡單、原生 PHP、可選解析器
Yii 2PHP 模板佈局、區塊、小部件

掌握 PHP 嵌入 HTML 基礎,是理解現代框架視圖層運作的關鍵。建議專案啟動即引入成熟模板引擎,專注業務邏輯開發。

copyright © 萬盛學電腦網 all rights reserved