You are here:  » Convert CSV to XML


Convert CSV to XML

Submitted by bayuobie on Sat, 2013-07-27 09:55 in

Hi Dave..seems i've not seen any post regarding converting csv to xml. Any help or example on that will do. Regards.

Submitted by support on Sat, 2013-07-27 10:30

Hi bayuobie,

Sure, this can be done - as a simple generic solution, consider the following example, which creates a document element of <records> with each record output within a <record> element. The only caveat would be that all field names are valid XML element names so i've included an str_replace call to ensure that any spaces are converted to underscores in the element names of each field (created from each key in $record)...

<?php
  header
("Content-Type: text/xml");
  require(
"MagicParser.php");
  function 
myRecordHandler($record)
  {
    print 
"<record>";
    foreach(
$record as $key => $value)
    {
      
$key str_replace(" ","_",$key);
      print 
"<".$key."><![CDATA[".$value."]]></".$key.">";
    }
    print 
"</record>";
  }
  
$filename "data.csv";
  
$formatString "csv|44|1|34";
  print 
"<records>";
  
MagicParser_parse($filename,"myRecordHandler",$formatString);
  print 
"</records>";
?>

Simply edit $filename and $formatString as required for your CSV source, and that should do the trick!

Hope this helps!
Cheers,
David
--
MagicParser.com

Submitted by bayuobie on Sat, 2013-07-27 10:59

Thanks Dave for the quick turn-around solution. It worked fine.