PHP 网站渲染代码设置指南

在 PHP 网站中设置渲染代码通常涉及以下几个方面:

1. 基本 PHP 页面渲染


php

<?php
// 设置内容类型为 HTML
header('Content-Type: text/html; charset=utf-8');

// 简单的 PHP 渲染示例
$title = "我的网站";
$content = "欢迎来到我的 PHP 渲染网站!";
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($title); ?></title>
</head>
<body>
    <h1><?php echo htmlspecialchars($title); ?></h1>
    <p><?php echo nl2br(htmlspecialchars($content)); ?></p>
    
    <?php
    // 动态生成列表
    $items = ['首页', '产品', '关于我们', '联系方式'];
    echo '<ul>';
    foreach ($items as $item) {
        echo '<li>' . htmlspecialchars($item) . '</li>';
    }
    echo '</ul>';
    ?>
</body>
</html>

2. 使用模板引擎(如 Twig)

首先安装 Twig(通过 Composer):


composer require "twig/twig:^3.0"

然后使用:


php

<?php
require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
    'cache' => 'cache',
]);

// 渲染模板
echo $twig->render('index.html', [
    'title' => '使用Twig渲染',
    'items' => ['苹果', '香蕉', '橙子']
]);

在 templates/index.html 中:


html

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <ul>
        {% for item in items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

3. 输出缓冲控制


php

<?php
// 开启输出缓冲
ob_start();

// 这里可以输出内容
echo "这部分内容会被缓冲";

// 获取缓冲内容并清空缓冲区
$content = ob_get_clean();

// 处理内容(例如替换某些字符串)
$content = str_replace('苹果', '橙子', $content);

// 输出最终内容
echo $content;

4. JSON 渲染(API 响应)


php

<?php
header('Content-Type: application/json; charset=utf-8');

$data = [
    'status' => 'success',
    'message' => '数据获取成功',
    'data' => [
        'user' => [
            'id' => 123,
            'name' =>
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐