How to Generate CSV File from XML Data in PHP
John Mwaniki / Updated on 07 Jul 2024When working with data, you may need to transform it from one format to another.
One of the many transformations is from XML (eXtensible Markup Language) to CSV (Comma-Separated Values), especially when dealing with diverse data sources.
XML is similar to HTML, comprising text data within self-describing tags. On the other hand, CSV has a simple, tabular format that is compatible with spreadsheet software (e.g., Microsoft Excel, LibreOffice Calc, Google Sheets, etc).
Common reasons for converting data to CSV include:
- Compatibility: Many applications, databases, and tools prefer CSV for its simplicity, making it easier to import and analyze data.
- Efficiency: CSV files are generally smaller and faster to process than XML files, making them more efficient for certain operations.
- Interoperability: CSV is a universal format that various platforms and programming languages can easily consume.
In this article, I'll take you through the process of generating a CSV file from XML data using PHP, providing an illustrative and practical example.
Converting XML to CSV file using PHP
PHP provides in-built ways to generate CSV files from XML data.
We will work with the XML data below comprising of three records, each consisting of a person's details (name, age, gender, and country).
<people>
<person>
<name>John Doe</name>
<age>30</age>
<gender>Male</gender>
<country>Uganda</country>
</person>
<person>
<name>Amina Hussein</name>
<age>27</age>
<gender>Female</gender>
<country>Saudi Arabia</country>
</person>
<person>
<name>David Johnson</name>
<age>32</age>
<gender>Male</gender>
<country>United Kingdom</country>
</person>
</people>
This data may be stored in a file or string. We will use the SimpleXML extension in PHP to load and parse XML data, convert it into CSV format, and store it in a .csv
file.
<?php
// Sample XML data in a string
$xmldata = '<people>
<person>
<name>John Doe</name>
<age>30</age>
<gender>Male</gender>
<country>Uganda</country>
</person>
<person>
<name>Amina Hussein</name>
<age>27</age>
<gender>Female</gender>
<country>Saudi Arabia</country>
</person>
<person>
<name>David Johnson</name>
<age>32</age>
<gender>Male</gender>
<country>United Kingdom</country>
</person>
</people>';
// Loading XML string to a SimpleXML object
$xml = simplexml_load_string($xmldata);
// Open CSV file for writing
$csvFile = fopen('data.csv', 'w');
// Adding the header to the CSV
$header = array_keys((array) $xml->person[0]);
fputcsv($csvFile, $header);
// Adding XML records as rows in CSV file
foreach ($xml->person as $person) {
fputcsv($csvFile, (array) $person);
}
// Closing the CSV file
fclose($csvFile);
?>
When executed, this code generates a new CSV file named "data.csv" in the same directory. If a file with that name exists in the directory, then it's overwritten.
The file's content:
name,age,gender,country
"John Doe",30,Male,Uganda
"Amina Hussein",27,Female,"Saudi Arabia"
"David Johnson",32,Male,"United Kingdom"
When opened with Microsoft Excel, the file looks like below.
Code Explanation
We parsed the XML data from a string ($xmldata) into a SimpleXML object using the simplexml_load_string()
function. If the XML data was stored in a file instead of a string, then we would have used the simplexml_load_file()
function with the filepath and name.
We then used the fopen() function, which is used for opening files. The first argument specifies the file's name and the second argument specifies the access mode in which we want to open it. When opening a file to write only, which is our case, we use the w
mode. If a file doesn't exist, this mode creates a new file. It places a file pointer at the beginning of the file.
The SimpleXMLElement Object ($xml) comprises an array of three elements, all being objects. We used the index 0, i.e., $xml->person[0]
to access and get the first object from the array. We then used the array_keys()
function to obtain the keys ("name", "age", "gender", and "country") as an array from the key-value pairs in the object to use them as the CSV file header. The header is simply the first line/row of the CSV file, whose content acts as the heading for the respective columns.
Using the fputcsv()
function, we added the header to the CSV file. The first argument specifies the open file to write to, while the second specifies an array of data to write in the file.
Using the foreach()
loop, we iterated through the array elements, forming an array of the values (e.g, ["John Doe", "30", "Male", "Uganda"]) and adding each record at a time to the CSV file using the fputcsv()
function in the same way as with the header.
Lastly, we used the fclose()
function to close the file stream.
That's it!
Now you know how to generate CSV files from XML data using PHP. I hope you enjoyed the article and found it helpful.