Witam, napisałem małą klasę do generowania plików XML z tablicy (jedno lub wielowymiarowej).
<?php
class XMLCreate
{
private $DOMDocument;
private $DOMElement;
public function __construct
(array $array, $rootNode = 'root') {
$this -> DOMDocument = new DOMDocument ('1.0', 'UTF-8');
$this -> createNode ($this -> DOMDocument -> appendChild ($this -> DOMDocument -> createElement ($rootNode)), $array);
}
private function createNode
(DOMElement
$DOMElement, array $data) {
foreach ($data as $key => $value)
{
$key = ltrim ($key, '01234567890');
{
$this -> createNode ($DOMElement -> appendChild ($this -> DOMDocument -> createElement ($key)), $value);
}
else if (substr ($key, 0, 1) == '@') {
$DOMElement -> setAttribute
(substr ($key, 1
), $value); }
else
{
$DOMElement -> appendChild ($this -> DOMDocument -> createElement ($key, $value));
}
}
}
public function save ()
{
return $this -> DOMDocument -> saveXML ();
}
}
?>
Sposób użycia:
<?php
(
'@time' => time (), // @ - oznacza że dany index będzie atrybutem elementu, a wartość index'u zostanie zmieniona na wartość atrybutu.
(
'name' => 'Jan',
'surname' => 'Kowalski',
(
'city' => 'Tarnow',
'postalCode' => '33-100',
),
'0interests' => array // Jak wiadomo nazwa elementu nie może zaczynać się od cyfry. Początkowe cyfry zos aną usunięte i zostanie stworzonych kilka elementów o tej samej nazwie.
(
'name' => 'Informatyka',
),
(
'name' => 'Sport',
),
),
);
$XML = new XMLCreate ($array); // Jako drugi, nieobowiązkowy argument możemy podać nazwę głównego węzła.
?>