Convert XML to CSV in PHP

By: David Thomas  

Here is an useful PHP code snippet to Output XML string as CSV with first row as column headers

<?php

    // In this case XML is 
    // <records>
    //  <record>...</record>
    //  <record>...</record>
    // </records>

  if($xml = simplexml_load_string($string)){
    // Keep up to 12MB in memory, if becomes bigger write to temp file
    $file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+');
    if($row = get_object_vars($xml->record[0])){ // First record
      // First row contains column header values
      foreach($row as $key => $value){
        $header[] = $key;
      }
      fputcsv($file, $header,',','"');
      foreach ($xml->record as $record) {
        fputcsv($file, get_object_vars($record),',','"');
      }
      rewind($file);
      $output = stream_get_contents($file);
      fclose($file);
      return $output;
    }else{
      return '';
    }
  }

?>



Archived Comments

1. Thanks. It was really useful :)
View Tutorial          By: ehsan at 2016-07-29 11:37:14

2. nice tutorial.I found this .
thank for the sharing.

View Tutorial          By: Bilal at 2015-01-18 07:47:02

3. thank for the sharing.
View Tutorial          By: likelove at 2014-11-22 12:41:58

4. nice tutorial
View Tutorial          By: Raman at 2014-11-13 07:47:11


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial