Blog about Web Programming and Electronics
💬 👤
back Back to blog
Programming

How to Convert an XML File to CSV with PHP

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:

  1. Path Setup: Define where your XML file is located and what the new CSV file will be named.
  2. Loading with SimpleXML: The simplexml_load_file function converts XML into an object that we can traverse with a loop.
  3. Setting Headers: Define the column names that will appear in the first row of the CSV file.
  4. 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}";
?>
back Back to blog