使用Php将元素附加到Xml文件

时间:2013-08-01 13:59:36

标签: php xml

我得到了像

这样的Xml文件
<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>`

我需要最短的方式来追加它

3 个答案:

答案 0 :(得分:1)

使用addChildaddAttribute

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

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

答案 1 :(得分:1)

由于您使用的是DOMDocument,这就是您所需要的:

$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);

答案 2 :(得分: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();