Here is the code for creating XML using DOM, very simple and straight forward.
I found this code from the book "PHP HACKS" by Jack D. Herrington, I thought it was worth sharing.
$books = array(
array(
id=>1,
author => "Jack",
name => "code generation in action"
),
array(
id=>2,
author => "Jack",
name => "podcasting Hacks"
),
array(
id=>3,
author => "Jack",
name => "best of PHP"
)
);
$dom = new DomDocument('1.0');
$dom->formatOutput = true;
$root = $dom->createElement("books");
$dom->appendChild($root);
foreach($books as $book){
$bn = $dom->createElement("book");
$bn->setAttribute('id',$book['id']);
$author = $dom->createElement("author");
$author->appendChild($dom->createTextNode($book['author']));
$bn->appendChild($author);
$name = $dom->createElement("name");
$name->appendChild($dom->createTextNode($book['name']));
$bn->appendChild($name);
$root->appendChild($bn);
}
header("content-type: text/xml");
echo $dom->saveXML();
?>
No comments:
Post a Comment