Thursday, December 11, 2008

Create XML the Right way

I was working in PHP to convert my query results into XML, even though we could create this XML using normal XML header type and printing in all the tags. The problem with this type of development is that you can easily go wrong and encoding special characters could be a pain.

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: