DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
From Database Records To XML
Here is a quick way to convert database records to XML using XML::Simple.
#!/usr/bin/perl
use warnings;
use strict;
use XML::Simple;
use DBI;
my $dbh = DBI->connect('DBI:mysql:MYDATABASE','user','password')
or die DBI->errstr;
# Get an array of hashes
my $recs = $dbh->selectall_arrayref('SELECT * FROM contents',{ Columns => {} });
# Convert to XML where each hash element becomes an XML element
my $xml = XMLout( {record => $recs}, NoAttr => 1 );
print $xml;
$dbh->disconnect;
For a table with fields named "id", "entry", and "modified", the output would be:
<opt>
<record>
<id>1</id>
<entry>1932 - 1939</entry>
<modified>2005-04-15 22:24:44</modified>
</record>
<record>
<id>2</id>
<entry>Yet another entry</entry>
<modified>2005-04-15 22:25:00</modified>
</record>
<record>
<id>3</id>
<entry>More stuff here</entry>
<modified>2005-04-15 22:25:13</modified>
</record>
</opt>





