XML is excellent for data exchange, but when we want to process it in Excel or import it into a database, CSV format is much more convenient. Below is a PHP script that automates this conversion.
Key Script Steps:
- Path Setup: Define where your XML file is located and what the new CSV file will be named.
- Loading with SimpleXML: The
simplexml_load_filefunction converts XML into an object that we can traverse with a loop. - Setting Headers: Define the column names that will appear in the first row of the CSV file.
- Writing: We use
fputcsv, which ensures proper separation with commas or semicolons.
<?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 (adapt to your structure)
$headers = ['ID', 'Name', 'Price'];
fputcsv($csv, $headers);
// Iterate through elements (in case there are <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 is located at: {$outputFilePath}";
?>