Programming Tutorials

Convert XML to CSV in PHP

By: David Thomas in PHP Tutorials on 2014-10-06  

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 '';
    }
  }

?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)