PHP Conference Japan 2024

DOMDocument::xinclude

(PHP 5, PHP 7, PHP 8)

DOMDocument::xinclude 在 DOMDocument 物件中替換 XInclude

說明

public DOMDocument::xinclude(int $options = 0): int|false

此方法會在 DOMDocument 物件中替換 » XInclude

注意:

由於 libxml2 會自動解析實體,如果包含的 XML 檔案附加了 DTD,此方法將會產生非預期的結果。

參數

options

libxml 選項常數位元 OR

傳回值

傳回文件中 XInclude 的數量,如果處理過程中發生錯誤則傳回 -1,如果沒有進行任何替換則傳回 false

範例

範例 #1 DOMDocument::xinclude() 範例

<?php

$xml
= <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>其他人的書籍..</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml 找不到</error>
</xi:fallback>
</xi:include>
</para>
</chapter>
EOD;

$dom = new DOMDocument;

// 產生易讀的輸出
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// 載入上方定義的 XML 字串
$dom->loadXML($xml);

// 替換 xincludes
$dom->xinclude();

echo
$dom->saveXML();

?>

上述範例將會輸出類似以下的內容

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

新增筆記

使用者貢獻的筆記 1 則筆記

nicolas_rainardNOSPAM at yahoo dot fr
17 年前
如果您使用 loadXML() 方法而不是 load() 方法(例如,在載入和解析 XML 字串之前先進行處理),您將會在使用 xinclude() 時遇到問題,因為解析器將不知道在哪裡找到要包含的檔案。
在 xinclude() 之前使用 chdir() 並沒有幫助。

解決方案是根據原始檔名設定 DOMDocument 物件的 documentURI 屬性,這樣一切就會正常運作!

<?php

$xml
= file_get_contents($file);
$xml = do_something_with($xml);

$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();

?>
To Top