2013-03-20 20 views
1

簡單的XML模板,像這樣的人:的DOMDocument :: loadXML的()爲XML的部分

structure.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<document> 
<book>first book</book> 
<book>second book</book> 
((other_books)) 
</document> 

book_element.xml:

<book>((name))</book> 

而且這個測試:

<?php 
Header("Content-type: text/xml; charset=UTF-8"); 
class XMLTemplate extends DOMDocument 
{ 
    private $_content_storage; 
    private $_filepath; 
    private $_tags; 

    public function XMLTemplate($sFilePath) 
    { 
     if(!file_exists($sFilePath)) throw new Exception("file not found"); 

     $this->_filepath = $sFilePath; 
     $this->_tags = []; 
     $this->_content_storage = file_get_contents($this->_filepath); 
    } 

    public function Get() 
    { 
     $this->merge(); 
     $this->loadXML($this->_content_storage); 
     return $this->saveXML(); 
    } 

    public function SetTag($sTagName, $sReplacement) 
    { 
     $this->_tags[ $sTagName ] = $sReplacement; 
    } 

    private function merge() 
    { 
     foreach($this->_tags as $k=>$v) 
     { 
      $this->_content_storage = preg_replace(
       "/\({2}". $k ."\){2}/i", 
       $v, 
       $this->_content_storage 
      ); 
     } 
     $this->_content_storage = preg_replace(
      "/\({2}[a-z0-9_\-]+\){2}/i", 
      "", 
      $this->_content_storage 
     ); 
    } 
} 

$aBooks = [ 
    "troisième livre", 
    "quatrième livre" 
]; 

$Books = ""; 

foreach($aBooks as $bookName) 
{ 
    $XMLBook = new XMLTemplate("book_element.xml"); 
    $XMLBook->SetTag("name", $bookName); 
    $Books .= $XMLBook->Get(); 
} 

$XMLTemplate = new XMLTemplate("test.xml"); 

$XMLTemplate->SetTag("other_books", $Books); 
echo $XMLTemplate->Get(); 
?> 

給我犯錯或者:

警告:DOM文檔:: loadXML的():僅在所述實體文檔的開始允許XML聲明,行:5

由於loadXML的()方法自動的聲明添加到內容,但我需要在上面的最終模板中注入部分xml。如何禁用這個煩人的自動添加並讓我使用我的聲明?或另一個想法來解決這個問題?

回答

1

如果您不喜歡該錯誤,並且希望保存您希望在沒有XML聲明的情況下合併的文檔,只需保存文檔元素而不是整個文檔。

請參見下面的示例代碼(online-demo)這兩種型號:

$doc = new DOMDocument(); 
$doc->loadXML('<root><child/></root>'); 

echo "The whole doc:\n\n"; 
echo $doc->saveXML(); 

echo "\n\nThe root element only:\n\n"; 
echo $doc->saveXML($doc->documentElement); 

輸出爲如下:

The whole doc: 

<?xml version="1.0"?> 
<root><child/></root> 


The root element only: 

<root><child/></root> 

這大概應該已經爲你有所幫助。此外,libxml還有一個常量,可以用它來控制是否輸出XML聲明。但我從來沒有使用過它:

LIBXML_NOXMLDECL(整數)

刪除保存文檔

注意當XML聲明:僅適用於xml庫[Libxml> = 2.6.21

來自:http://php.net/libxml.constants

有關更多選項,請參閱鏈接,您可能希望將來使用這一個或另一個選項。

相關問題