Over a million developers have joined DZone.

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:



  
    1
    1932 - 1939
    2005-04-15 22:24:44
  
  
    2
    Yet another entry
    2005-04-15 22:25:00
  
  
    3
    More stuff here
    2005-04-15 22:25:13
  


Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}