-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
81 lines (61 loc) · 1.96 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
//function to convert csv to xml string
function convertCsvToXmlString($csv_string) {
// split rows into lines
$lines = explode(PHP_EOL, $csv_string);
// retrieve headers
$headers = explode(',', array_shift($lines));
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('policies');
$root = $doc->appendChild($root);
// Loop through each row creating a <policy> node with the correct data
foreach ($lines as $line)
{
$row = str_getcsv($line);
$container = $doc->createElement('policy');
foreach($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
echo $strxml;
}
function convertCsvToXmlFile($input_file, $output_file) {
// Open csv file for reading
$inputFile = fopen($input_file, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('policies');
$root = $doc->appendChild($root);
// Loop through each row creating a <policy> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('policy');
foreach($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
$handle = fopen($output_file, "w");
fwrite($handle, $strxml);
fclose($handle);
}
convertCsvToXmlFile("products_20221027035913.csv", "xml/products_20221027035913.xml");
?>