Logo Logo
Back to list
Razno

How to Convert XML to CSV using PHP

14. 03. 2026
How to Convert XML to CSV using PHP

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:

  1. Path Preparation: Define the location of your XML source and the name of the output CSV file.
  2. Loading with SimpleXML: The simplexml_load_file function converts XML into an object that we can iterate through.
  3. Header Setup: Define the column names that will appear in the first row of your CSV file.
  4. 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}";
?>

Hvala za obisk! Dodajam politiko zasebnosti.

© 2024 Vse pravice pridržane.

Vam je koda pomagala? Če želite podpreti moj trud pri pripravi vodičev in vzdrževanju strani, mi lahko namenite donacijo za kavo.