1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mathielen\DataImport\Writer; |
4
|
|
|
|
5
|
|
|
use Ddeboer\DataImport\Writer\WriterInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Writes data to a xml file. |
9
|
|
|
*/ |
10
|
|
|
class XmlWriter implements WriterInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var \DOMDocument |
14
|
|
|
*/ |
15
|
|
|
private $xml; |
16
|
|
|
private $filename; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var \DOMNode |
20
|
|
|
*/ |
21
|
|
|
private $rootNode; |
22
|
|
|
|
23
|
|
|
private $rowNodeName; |
24
|
|
|
private $rootNodeName; |
25
|
|
|
|
26
|
1 |
|
public function __construct(\SplFileObject $file, $rowNodeName = 'node', $rootNodeName = 'root') |
27
|
|
|
{ |
28
|
1 |
|
$this->filename = $file->getRealPath(); |
29
|
1 |
|
$this->rowNodeName = $rowNodeName; |
30
|
1 |
|
$this->rootNodeName = $rootNodeName; |
31
|
1 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
*/ |
36
|
1 |
|
public function prepare() |
37
|
|
|
{ |
38
|
1 |
|
$this->xml = new \DOMDocument(); |
39
|
1 |
|
$this->rootNode = $this->xml->createElement($this->rootNodeName); |
40
|
1 |
|
$this->xml->appendChild($this->rootNode); |
41
|
|
|
|
42
|
1 |
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* (non-PHPdoc). |
47
|
|
|
* |
48
|
|
|
* @see \Ddeboer\DataImport\Writer\WriterInterface::writeItem() |
49
|
|
|
*/ |
50
|
1 |
|
public function writeItem(array $item) |
51
|
|
|
{ |
52
|
1 |
|
$newNode = $this->xml->createElement($this->rowNodeName); |
53
|
|
|
|
54
|
|
|
//attributes |
55
|
1 |
|
if (isset($item['@attributes']) && is_array($item['@attributes'])) { |
56
|
1 |
|
foreach ($item['@attributes'] as $key => $value) { |
57
|
1 |
|
$attr = $this->xml->createAttribute($key); |
58
|
1 |
|
$attr->value = $value; |
59
|
1 |
|
$newNode->appendChild($attr); |
60
|
|
|
} |
61
|
1 |
|
unset($item['@attributes']); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
//values |
65
|
1 |
|
foreach ($item as $key => $value) { |
66
|
1 |
|
$node = $this->xml->createElement($key); |
67
|
1 |
|
$node->nodeValue = $value; |
68
|
1 |
|
$newNode->appendChild($node); |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
$this->rootNode->appendChild($newNode); |
72
|
|
|
|
73
|
1 |
|
return $this; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* {@inheritdoc} |
78
|
|
|
*/ |
79
|
1 |
|
public function finish() |
80
|
|
|
{ |
81
|
1 |
|
$this->xml->save($this->filename); |
82
|
|
|
|
83
|
1 |
|
return $this; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|