`xmllint` 隸屬 `libxml2`,Linux 系統預裝或 `yum/apt install libxml2` 可用。支援 XML 格式化、驗證、XPath 查詢、HTML 解析、Schema 校驗。
| 參數 | 功能 | 典型用法 |
|---|---|---|
| --format | 美化輸出(縮進、換行) | `xmllint --format file.xml` |
| --noblanks | 移除無意義空白(壓縮) | `xmllint --noblanks file.xml` |
| --html | HTML 解析模式 | `... | xmllint --html --xpath "..." -` |
| --xpath | XPath 1.0 查詢 | `xmllint --xpath "//book/title" file.xml` |
| --schema | XSD Schema 校驗 | `xmllint --schema schema.xsd file.xml` |
| --noout | 僅校驗不輸出文檔 | `xmllint --noout --schema schema.xsd file.xml` |
# 提取 IP 查詢結果
curl -s "https://www.example.com/ip/?q=8.8.8.8" | \
xmllint --html --xpath "//ul[@id='csstb']" - 2>/dev/null | \
sed 's/<[^>]*>//g'
# 輸出純文本結果:
# [您的查詢]:8.8.8.8
# 本站主數據: 美國
# ...
# 格式化 (易讀)
xmllint --format person.xml
# 輸出:
#
#
# ball
# 30
# male
#
# 壓縮 (傳輸)
xmllint --noblanks person.xml
# 輸出單行:
# ball 30 male
# person.xsd 定義 name/age/sex 結構與約束
xmllint --noout --schema person.xsd person.xml
# 通過: person.xml validates
# 失敗: 具體報錯行號、元素、約束違規詳情
`--schema` 驗證錯誤輸出到 **stderr** 而非 stdout,PHP `exec()` 預設只捕獲 stdout。
<?php
$cmd = "xmllint --noout --schema person.xsd person.xml 2>&1";
exec($cmd, $output, $retval);
if ($retval !== 0) {
var_dump($output); // 獲取詳細錯誤信息
} else {
echo "驗證通過";
}
關鍵:`2>&1` 將 stderr 重定向到 stdout。
# po.xml 採購訂單
# po.xsd 定義結構、類型、約束 (SKU 模式 \d{3}-[A-Z]{2})
xmllint --schema po.xsd po.xml
# 無錯誤輸出即通過
class XmlLint {
public static function validate($xmlPath, $xsdPath) {
$cmd = sprintf('xmllint --noout --schema %s %s 2>&1',
escapeshellarg($xsdPath), escapeshellarg($xmlPath));
exec($cmd, $out, $ret);
return [$ret === 0, $out];
}
public static function xpath($xmlPath, $xpath) {
$cmd = sprintf('xmllint --xpath %s %s 2>/dev/null',
escapeshellarg($xpath), escapeshellarg($xmlPath));
exec($cmd, $out);
return implode("\n", $out);
}
}
| 場景 | 推薦工具 |
|---|---|
| PHP 內部解析 | DOMDocument + DOMXPath (無外部依賴) |
| 命令行/腳本驗證 | xmllint (功能全、標準兼容) |
| 高效能流式處理 | XMLReader / SAX 解析器 |
| 複雜 XSLT 轉換 | xsltproc / libxslt |
`xmllint` 是 XML/HTML 命令行處理的瑞士軍刀,掌握其核心參數與 PHP 集成技巧,能高效解決結構化文檔驗證、提取、轉換需求。