forked from crosbymichael/php-csv-to-xml-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSVToXmlParser.php
62 lines (47 loc) · 1.22 KB
/
CSVToXmlParser.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
<?php
include_once("CSVParserBase.php");
/**
* Specific implementation to parse csv to an xml document
*/
class CSVToXmlParser extends CSVParserBase {
public $ItemName = 'item';
protected function ProcessArray($array) {
$startingIndex = 0;
$document = '';
if ($this->IsFirstRowHeader) {
$startingIndex = 1;
$this->HeaderArray = $array[0];
}
$columnCount = count($array[0]);
$document = "<?xml version=\"1.0\" ?>\n";
$document .= "<root>\n";
for ($i=$startingIndex; $i < count($array); $i++) {
$document .= $this->GetItemName();
for ($n=0; $n < $columnCount; $n++) {
$columnName = $this->GetColumnName($n);
$document .= sprintf(
"\t\t<%s>%s</%s>\n",
$columnName,
$array[$i][$n],
$columnName);
}
$document .= $this->GetItemName(true);
}
$document .= "</root>";
return $document;
}
private function GetColumnName($index) {
$name = 'column' . $index;
if ($this->HeaderArray != null &&
count($this->HeaderArray) > 0)
{
$name = $this->StripString(
$this->HeaderArray[$index]);
}
return $name;
}
private function GetItemName($close = false) {
$format = ($close) ? "\t</%s>\n" : "\t<%s>\n";
return sprintf($format, $this->ItemName);
}
}