参数与变量
PHP 用 XSLTProcessor 执行转换:加载 XML 和 XSL,importStylesheet 关联,transformToXML 输出结果。
流程
$xml = new DOMDocument(); $xml->load("data.xml"); $xsl = new DOMDocument(); $xsl->load("style.xsl"); $proc = new XSLTProcessor(); $proc->importStylesheet($xsl); echo $proc->transformToXML($xml);
浏览器端
现代浏览器有 XSLTProcessor JS API,也可以直接把 XML 关联 XSL(<?xml-stylesheet type="text/xsl" href="style.xsl"?>)自动渲染。
代码示例
<?php
// data.xml 和 style.xsl 已存在
$xml = new DOMDocument();
$xml->load("books.xml");
$xsl = new DOMDocument();
$xsl->load("books.xsl");
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
// 参数传递
$proc->setParameter("", "pageTitle", "我的书架");
// 转换输出
$html = $proc->transformToXML($xml);
echo $html;
// 保存结果
// file_put_contents("books.html", $html);
?>
📚 PHP 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
<?php ... ?> | PHP 代码块标记 |
echo "hello"; | 输出字符串 |
$name = "张三"; | 变量(以 $ 开头,无需声明类型) |
if ($x > 0) { } else { } | 条件判断 |
foreach ($arr as $k => $v) { } | 遍历数组(最常用) |
for ($i = 0; $i < 10; $i++) { } | 计数循环 |
function fn($a) { return $a; } | 定义函数 |
array("a" => 1) | 关联数组(PHP 的"字典") |
count($arr) | 数组长度 |
isset($x) / empty($x) | 变量是否存在 / 是否为空 |
$_GET["key"] / $_POST["key"] | 获取表单 / 查询参数 |
$_SESSION["user"] | 会话数据读写(需 session_start()) |
$_COOKIE["key"] | 读取 Cookie |
header("Location: /index.php"); | 页面跳转 |
mysqli_connect($host, $user, $pass, $db) | 连接 MySQL(旧接口,新项目用 PDO) |
new PDO($dsn, $user, $pass) | 连接 MySQL(推荐,防 SQL 注入) |
$stmt->prepare($sql) | 预处理语句(防 SQL 注入) |
htmlspecialchars($str) | HTML 转义(防 XSS) |
strlen($s) / mb_strlen($s) | 字符串长度 |
explode(",", $s) / implode(",", $arr) | 字符串拆分 / 拼接 |
json_encode($arr) / json_decode($s) | 数组与 JSON 互转 |
include / require | 引入文件(require 报错即停) |
date("Y-m-d H:i:s") | 当前时间格式化 |
$_FILES["file"] | 文件上传数据 |
file_put_contents($path, $data) | 写入文件 |