Generic XML to CSV Converter

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

Some times you might have a legacy system that is built around csv or similar and you need to import an XML data source into this system.

Of course one possibility is to build full XML handling capabilities into the system. Perhaps a more sane solution is to simply convert the XML to CSV so that the legacy system does not have to be touched.

This little snippet will generally take an XML file and create a CSV file that should be useable. Of course its impossible to guarantee this for every XML file as its such a widely varied format, however in general this should work.

$xml = simplexml_load_file('feed.xml');
$outstream = fopen('feed.csv','w');
$header=false;
foreach($xml as $k=>$details){
    if(!$header){
        fputcsv($outstream,array_keys(get_object_vars($details)));
        $header=true;
    }
    fputcsv($outstream,get_object_vars($details));
}
fclose($outstream);

Tags: phpfunctionxmldatatipconvertlegacy