首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 使用 xmllint 命令處理 XML/HTML:格式化、驗證、XPath 提取與 Schema 校驗完整指南

     編輯:PHP 綜合知識

工具介紹

`xmllint` 隸屬 `libxml2`,Linux 系統預裝或 `yum/apt install libxml2` 可用。支援 XML 格式化、驗證、XPath 查詢、HTML 解析、Schema 校驗。

核心參數速查

參數功能典型用法
--format美化輸出(縮進、換行)`xmllint --format file.xml`
--noblanks移除無意義空白(壓縮)`xmllint --noblanks file.xml`
--htmlHTML 解析模式`... | xmllint --html --xpath "..." -`
--xpathXPath 1.0 查詢`xmllint --xpath "//book/title" file.xml`
--schemaXSD Schema 校驗`xmllint --schema schema.xsd file.xml`
--noout僅校驗不輸出文檔`xmllint --noout --schema schema.xsd file.xml`

實戰場景一:HTML 頁面 XPath 數據提取

# 提取 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
# 本站主數據: 美國
# ...

實戰場景二:XML 格式化與壓縮

# 格式化 (易讀)
xmllint --format person.xml
# 輸出:
# 
# 
#   ball
#   30
#   male
# 

# 壓縮 (傳輸)
xmllint --noblanks person.xml
# 輸出單行:
# ball30male

實戰場景三:XSD Schema 驗證

# person.xsd 定義 name/age/sex 結構與約束
xmllint --noout --schema person.xsd person.xml
# 通過: person.xml validates
# 失敗: 具體報錯行號、元素、約束違規詳情

PHP 集成關鍵:stderr 捕獲

`--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。

完整範例:採訂單 XML 驗證

# po.xml 採購訂單
# po.xsd 定義結構、類型、約束 (SKU 模式 \d{3}-[A-Z]{2})
xmllint --schema po.xsd po.xml
# 無錯誤輸出即通過

進階技巧

  • XInclude 處理:`xmllint --xinclude file.xml` 展開 ``
  • DTD 驗證:`xmllint --valid --dtdvalid dtd.dtd file.xml`
  • 命名空間 XPath:`xmllint --xpath "//ns:element" --shell file.xml` 交互模式註冊前綴
  • 流式處理大文件:`xmllint --stream --pattern "//item" huge.xml` (低內存)

PHP 封裝建議

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 集成技巧,能高效解決結構化文檔驗證、提取、轉換需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved