2013-08-01 159 views
0

我的XML文件一樣追加元素到XML文件用PHP

<root> 
<firstchild id="1"> 
<page name="main"> 
</page> 
</firstchild> 
</root> 

我想在PHP的則firstChild ID = 「1」 加頁。我如何添加?

$xml='<page name="second"></page>'; 
    $doc = new DOMDocument(); 
    $doc->load($filename); 
    $fragment = $doc->createDocumentFragment(); 
    $fragment->appendXML($xml); 
    $doc->documentElement->appendChild($fragment); 
    $doc->save($filename); 

是否沒有任何方法appendXml? 我可能會增加它像

`<page name="second"> 
<inlude file="1.png"></inlude> 
<inlude file="2.png"></inlude> 
</page>` 

我需要最簡單的辦法將其追加

+1

添加PHP代碼,顯示你已經嘗試 – tlenss

+0

這已經被問了一遍又一遍的SO。只要看看像http://stackoverflow.com/questions/7098093/how-to-append-to-a-xml-file-with-php-preferably-with-simplexml?rq=1或http: //stackoverflow.com/questions/2393270/use-domdocument-to-append-elements-in-a-xml-file?rq=1。 –

回答

1

由於您使用DOM文檔,這就是你所需要的:

$doc = new DOMDocument(); 
$doc->load($filename); 
$firstchild = $doc->getElementsByTagName('firstchild')->item(0); 
$newPage = $doc->createDocumentFragment(); 
$newPage->appendXML('<page name="second"> 
<inlude file="1.png"></inlude> 
<inlude file="2.png"></inlude> 
</page>'); 
$firstchild->appendChild($newPage); 
$doc->save(filename); 
+0

感謝這幾乎是我所需要的。 – user2622044

1

使用addChildaddAttribute

$xml = simplexml_load_string($data); 
$page = $xml->firstchild->addChild("page"); 
$page->addAttribute("name", "Page name"); 
echo $xml->saveXML(); 

演示:http://codepad.org/u78S8rFK

+0

非常感謝它的簡短方法。但首先我需要找到id attr 1 – user2622044

0

這可能會幫助你

$xml = new DomDocument(); 
$xml->loadXml('<foo><baz><bar>Node Contents</bar></baz></foo>');  

//grab a node 
$xpath = new DOMXPath($xml);  
$results = $xpath->query('/foo/baz'); 
$baz_node_of_xml = $results->item(0); 

//create a new, free standing node 
$new_node = $xml->createElement('foobazbar'); 

//create a new, freestanding text node 
$text_node = $xml->createTextNode('The Quick Brown Fox'); 

//add our text node 
$new_node->appendChild($text_node); 

//append our new node to the node we pulled out 
$baz_node_of_xml->appendChild($new_node); 

//output original document. $baz_nod_of_xml is 
//still considered part of the original $xml DomDocument 
echo $xml->saveXML();