Skip to content

Instantly share code, notes, and snippets.

@amityweb
Last active May 12, 2022 18:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amityweb/479a0ca0e5ef39a786bc to your computer and use it in GitHub Desktop.
Save amityweb/479a0ca0e5ef39a786bc to your computer and use it in GitHub Desktop.
CSV to XML using PHP
<?php
// Map CSV file to array
$rows = array_map('str_getcsv', file('data.csv'));
$header = array_shift($rows);
$data = array();
foreach ($rows as $row)
{
$data[] = array_combine($header, $row);
}
// Process Data if need be
foreach($data AS $key => $val)
{
// Processing here
}
//Creates XML string and XML document using the DOM
$xml = new DomDocument('1.0', 'UTF-8');
//Add root node
$root = $xml->createElement('root');
$xml->appendChild($root);
// Add child nodes
foreach($data AS $key => $val)
{
$entry = $xml->createElement('entry');
$root->appendChild($entry);
foreach($val AS $field_name => $field_value)
{
$field_name = preg_replace("/[^A-Za-z0-9]/", '', $field_name); // preg_replace has the allowed characters
$name = $entry->appendChild($xml->createElement($field_name));
$name->appendChild($xml->createCDATASection($field_value));
}
}
// Set the formatOutput attribute of xml to true
$xml->formatOutput = true;
// Output to screen
//header('Content-Type: text/xml');
//echo $xml->saveXML();
// Save as file
$xml->save('xml-import.xml'); // save as file
?>
@mipoes75
Copy link

mipoes75 commented Jun 26, 2017

someone knows how to make the code output xml including also the rss version like in the attchment please?
Thank you all for your help!

2017-06-26_11-44-00

@william0471
Copy link

How to Download Automatically an xml format file direct from my computer or in download folder after converted into CSV TO XML

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment