1

I got Xml File like

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

I want to add page for firstchild id="1" in php. How can I add?

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

Is there not any method appendXml? I may add it like

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

I need Shortest Way to Append it

user2622044
  • 185
  • 3
  • 4
  • 14
  • 1
    Add the PHP code that shows you have tried – tlenss Aug 01 '13 at 14:06
  • This has been asked over and over again in SO. Just take a look at related questions like http://stackoverflow.com/questions/7098093/how-to-append-to-a-xml-file-with-php-preferably-with-simplexml?rq=1 or http://stackoverflow.com/questions/2393270/use-domdocument-to-append-elements-in-a-xml-file?rq=1. – Rolando Isidoro Aug 01 '13 at 14:09

2 Answers2

1

Use addChild and addAttribute:

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

Demo: http://codepad.org/u78S8rFK

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

Since you are using DOMDocument, that's what you need:

$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);
klkvsk
  • 670
  • 4
  • 7