當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP DOMDocument xinclude()用法及代碼示例


DOMDocument::xinclude()函數是PHP中的一個內置函數,用於替代DOMDocument對象中的XIncludes。

用法:

int DOMDocument::xinclude( int $options = 0 )

參數:此函數接受一個可選的單個參數$options,該參數包含libxml參數。


返回值:此函數返回文檔中XIncludes的數量;如果某些處理失敗,則返回-1;如果沒有替代,則返回FALSE。

以下示例說明了PHP中的DOMDocument::xinclude()函數:

範例1:在此程序中,我們將包括從XML.new.xml到index.php。

  • new.xml
    <?xml version='1.0'?> 
    <disclaimer> 
      <p> 
        This is the content from new.xml 
        included using xinclude. 
      </p> 
    </disclaimer>
  • index.php
    <?php 
    $xml = <<<EOD 
    <?xml version="1.0" ?> 
    <root xmlns:xi="http://www.w3.org/2001/XInclude"> 
      <xi:include href="new.xml"> 
      </xi:include> 
    </root> 
    EOD; 
      
    // Create a new DOMDocument 
    $dom = new DOMDocument(); 
      
    // let's have a nice output 
    $dom->preserveWhiteSpace = false; 
    $dom->formatOutput = true; 
      
    // load the XML string defined above 
    $dom->loadXML($xml); 
      
    // substitute xincludes 
    $dom->xinclude(); 
      
    echo $dom->saveXML(); 
    ?>
  • 輸出:
    This is the content from new.xml included using xinclude.

範例2:在此程序中,如果xinclude失敗,我們將添加一個後備。

  • index.php
    <?php 
    $xml = <<<EOD 
    <?xml version="1.0" ?> 
    <root xmlns:xi="http://www.w3.org/2001/XInclude"> 
      <xi:include href="wrong_name.xml"> 
       <xi:fallback> 
        <error>xml not found</error> 
       </xi:fallback> 
      </xi:include> 
    </root> 
    EOD; 
      
    // Create a new DOMDocument 
    $dom = new DOMDocument(); 
      
    // let's have a nice output 
    $dom->preserveWhiteSpace = false; 
    $dom->formatOutput = true; 
      
    // load the XML string defined above 
    $dom->loadXML($xml); 
      
    // substitute xincludes 
    $dom->xinclude(); 
      
    echo $dom->saveXML(); 
    ?>
  • 輸出:
    xml not found

參考: https://www.php.net/manual/en/domdocument.xinclude.php



相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMDocument xinclude() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。