PHP: XML to CSV

Posted on Jun 25, 2013
To create a CSV file from a XML in PHP 5.0+ it's very easy. We will use the SimpleXML extension that come from PHP 5.0+
SimpleXML reads an entire XML into an object that we can iterate through his properties. To write to the csv output file we will use fputcsv.

fputcsv formats a line as CSV and writes it to the file. Suppose we are having this XML file named phones.xml:
<?xml version='1.0'?>
<phones>
<phone>
<price>1500</price>
<color>black</color>
</phone>
<phone>
<price>14000</price>
<color>black</color>
</phone> 
<phone>
<price>5300</price>
<color>white</color>
</phone>
</phones>

First we should read our xml using simplexml_load_file passing the name of the file and returns an object with all the properties and values of the csv:
$xml = simplexml_load_file($filexml);

After reading it we should iterate through all the child nodes of phones and write it to the output file using fputcsv specifying the object,delimiter and enclosure. We should first convert the object into an array in order to write it to the csv:
foreach ($xml->phone as $phone) 
fputcsv($f, get_object_vars($phone),',','"');

Here is the complete source code that converts xml to csv in php 5.0:
<?
$filexml='phones.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$f = fopen('phones.csv', 'w');
foreach ($xml->phone as $phone) {
fputcsv($f, get_object_vars($phone),',','"');
}
fclose($f);
}
?>

Leave a comment:

Thank you for your comment. After a while, our moderators will add it.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

© Twiwoo 2023 Cookie Policy