Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.