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
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8