Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CSV to XML
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$csv = [];
if ($_FILES['csv']['error'] == 0) {
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if ($ext === 'csv') {
if (($handle = fopen($tmpName, 'r')) !== FALSE) {
// if the csv file is large
set_time_limit(0);
// Get the headers (row names) of the file
$headers = fgetcsv($handle);
// Create a new dom document using DomDocument class
$doc = new DomDocument('1.0', 'UTF-8');
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('urls');
$root = $doc->appendChild($root);
while (($row = fgetcsv($handle)) !== FALSE) {
$container = $doc->createElement('url');
foreach ($headers as $i => $header) {
$child = $doc->createElement(trim($header));
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
$handle = fopen("sitemap.xml", "w");
fwrite($handle, $strxml);
fclose($handle);
echo "The file is downloaded";
}
}
}
/*
The HTML form
<form action="csvToxml2.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" />
</form>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment