Jump to content

Please help me repair this code php export to xml file.


thuythu1

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.