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 )

__autoload() METHOD in PHP

Convert XML to CSV in PHP

Opening a Remote File in PHP

Function to force strict boolean values in PHP

Malware: global $ob_starting;

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Convert IP address to integer and back to IP address in PHP

Function to return number of digits of an integer in PHP

Function to sort array by elements and count of element in PHP

Latest Articles (in PHP)