thuythu1 Posted May 7, 2010 Share Posted May 7, 2010 Hello everybody! I am having this php code: <?php $doc = new DOMDocument(); $doc->formatOutput = true; if(!file_exists('data.xml')){ $doc->appendChild($doc->createElement('books')); $doc->save('data.xml'); } @$doc->load('data.xml'); //Searches for all elements with the "books" tag name $root = $doc->getElementsByTagName('books'); if($root->length == 0){ $doc->appendChild($doc->createElement('books')); } /* tao doi tuong documentfragment */ $f = $doc->createDocumentFragment(); $item = $doc->createElement('book'); $item->appendChild($doc->createElement('name', $_POST['name'])); $item->appendChild($doc->createElement('price', $_POST['price'])); $f->appendChild($item); $doc->documentElement->appendChild($f); $doc->save('data.xml'); echo $doc->saveXML(); ?> when i run this php code on webserver, the result xml file: <?xml version="1.0"?> <books> <book> <name>aaaaaaaaaaaaa</name> <price>bbbbbbbb</price> </book> <book> <name>aaaaaaaaaaaaa</name> <price>bbbbbbbb</price> </book> </books> how to repair the code php to result xm file like this ? (add <bookslict> </bookslist>) <?xml version="1.0"?> <books> <bookslist> <book> <name>aaaaaaaaaaaaa</name> <price>bbbbbbbb</price> </book> <book> <name>aaaaaaaaaaaaa</name> <price>bbbbbbbb</price> </book> </bookslist> </books> Please help me, thanks Quote Link to comment https://forums.phpfreaks.com/topic/200978-please-help-me-repair-this-code-php-export-to-xml-file/ Share on other sites More sharing options...
Adam Posted May 10, 2010 Share Posted May 10, 2010 When you create the books element, store the returned node so that you're able to append a child to it: $books = $doc->appendChild($doc->createElement('books')); Then using the returned node, append the booklist child to it: $blist = $book->appendChild($doc->createElement('booklist')); Then instead of appending the fragmented node to the root/books element (the "documentElement"), append it to the booklist element: $blist->appendChild($f); Should work as you want after that. Quote Link to comment https://forums.phpfreaks.com/topic/200978-please-help-me-repair-this-code-php-export-to-xml-file/#findComment-1055785 Share on other sites More sharing options...
Adam Posted May 10, 2010 Share Posted May 10, 2010 Then using the returned node, append the booklist child to it: $blist = $book->appendChild($doc->createElement('booklist')); Sorry, that should be $books->(...) Quote Link to comment https://forums.phpfreaks.com/topic/200978-please-help-me-repair-this-code-php-export-to-xml-file/#findComment-1055818 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.