Here's my current XML file (books.xml):
<?xml version="1.0"?>
<books>
<book>
<isbn>123456789098</isbn>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<edition>1</edition>
</book>
</books>
Please note that in this case, the edition is a number from 1 to 99, and that the ISBN has a length of 12 digits, contrary to the real-world concept of the book attribute.
I have an "add book" form and I want to save the collected data from that form (using post) by appending the new book to the already-existing XML file. What would be the best way to do this, in PHP? I am confused as to how to do it because the way I did it works half and half: either it saves an empty node or does nothing at all.
/*************************************
*code snippet of results.php
*************************************/
$doc = new DOMDocument();
$doc->load('books.xml');
$nodes = $doc->getElementsByTagName('books');
if($nodes->length > 0)
{
$b = $doc->createElement( "book" );
$isbn = $doc->createElement( "isbn" );
$isbn->appendChild(
$doc->createTextNode( $book['isbn'] ));
$b->appendChild( $isbn );
$title = $doc->createElement( "title" );
$title->appendChild(
$doc->createTextNode( $book['title'] ));
$b->appendChild( $title );
$author = $doc->createElement( "author" );
$author->appendChild(
$doc->createTextNode( $book['author'] ));
$b->appendChild( $author );
$edition = $doc->createElement( "edition" );
$edition->appendChild(
$doc->createTextNode( $book['edition'] ));
$b->appendChild( $edition );
$doc->appendChild( $b );
}
$doc->save('books.xml');
Thank you for your help.