I'm trying to nest multiple elements in my XML output using the PHP5 DOM.
I want to get this, but can't get a nested element to work. Is what I'm trying to do illegal?
Code:
<items>
<books>
<writers>
<author>
<name></name>
<title></title>
<publisher></publisher>
</author>
<author>
<name></name>
<title></title>
<publisher></publisher>
</author>
</writers>
</books>
</items>
PHP Code:
<?php
$books = array();
$books [] = array(
'title' => 'PHP Hacks',
'name' => 'Jack Herrington',
'publisher' => "O'Reilly"
);
$books [] = array(
'title' => 'Podcasting Hacks',
'name' => 'Jack Herrington',
'publisher' => "O'Reilly"
);
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement("items");
$doc->appendChild( $r );
foreach($books as $book) {
$b = $doc->createElement( "books" );
// nested element
$b = $doc->createElement( "writers" );
$b = $doc->createElement( "author" );
$name = $doc->createElement( "name" );
$name->appendChild($doc->createTextNode( $book['name'] ));
$b->appendChild( $name );
$title = $doc->createElement( "title" );
$title->appendChild($doc->createTextNode( $book['title'] ));
$b->appendChild( $title );
$publisher = $doc->createElement( "publisher" );
$publisher->appendChild($doc->createTextNode( $book['publisher'] ));
$b->appendChild( $publisher );
$r->appendChild( $b );
}
echo $doc->saveXML();
?>
Bookmarks