Hi there
I need to get XML file output from CSV. I've created part of the code (only as print()). But what I really need is to have a XML file with my data. Has anyone done something like this before?? Just to show me the correct path of doing things.
Thanks
Hello Milos,
The basic idea is;
1) Print the XML header
2) Parse your CSV, then for each row create an XML record
3) Print the XML footer
The only thing you need to be particularly careful about is making sure that the data you insert into the output stream is safe - in other words it is properly encoded. Below is a complete "generic" example; simply change the Format String in the call to MagicParser_parse() as required; and make sure that PHP is able to create the output file. In this example you will see that I have used a directory called "files" - so make sure that it is writable. Finally, just modify the code within the record handler function as per your input data.
<?php
require("MagicParser.php");
function xmlentities($text)
{
$search = array('&','<','>','"','\'');
$replace = array('&','<','>','"',''');
$text = str_replace($search,$replace,$text);
return $text;
}
function myRecordHandler($record)
{
global $outfile;
fwrite($outfile,"<record>";
foreach($record as $key => $value)
{
fwrite($outfile,"<".$key.">".xmlentities($value)."</".$key.">");
}
fwrite($outfile,"</record>";
}
$input = "data/filename.csv";
$output = "data/filename.xml";
$outfile = fopen($output,"w");
if (!$outfile) die("Could not create output file");
// output the XML header
fwrite($outfile,"<records>";
// parse the CSV to create records
MagicParser_parse($input,"myRecordHandler","csv|44|1|0");
// output the XML footer
fwrite($outfile,"</records>";
fclose($outfile);
?>
Hope this points you in the right direction!
Cheers,
David.