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 )

Different versions of PHP - History and evolution of PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP

Input Validation in PHP

Opening a Remote File in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Exception in module wampmanager.exe at 000F15A0 in Windows 8

Convert XML to CSV in PHP

Installing PHP and MySQL in windows, mac and linux

Decrypting files using GnuPG (GPG) via PHP

Install and use PHPUnit to test your PHP pages for errors.

Parent: child process exited with status 3221225477 -- Restarting

XMLRPC for PHP - A simple client and server program

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

Latest Articles (in PHP)