XML is great for data exchange, but for spreadsheet processing or database imports, the CSV format is much more practical. Below is a PHP script that automates this conversion.
Key Script Steps:
- Path Preparation: Define the location of your XML source and the name of the output CSV file.
- Loading with SimpleXML: The
simplexml_load_filefunction converts XML into an object that we can iterate through. - Header Setup: Define the column names that will appear in the first row of your CSV file.
- Writing Data: We use
fputcsv, which handles proper comma or semicolon separation automatically.
<?php
// File paths
$xmlFilePath = "data.xml";
$outputFilePath = "data.csv";
// Check if file exists
if (!file_exists($xmlFilePath)) {
die("Error: XML file does not exist.");
}
// Load XML
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) {
die("Error loading XML.");
}
// Open CSV for writing
$csv = fopen($outputFilePath, 'w');
// Write column headers (adjust to your structure)
$headers = ['ID', 'Name', 'Price'];
fputcsv($csv, $headers);
// Iterate through elements (assuming <item> elements in XML)
foreach ($xml->item as $item) {
$row = [
(string) $item->id,
(string) $item->name,
(string) $item->price,
];
fputcsv($csv, $row);
}
fclose($csv);
echo "Conversion successful! File saved at: {$outputFilePath}";
?>