<?php
namespace
Library;
class
XML
{
private
static
$version
=
"1.0"
;
private
static
$encoding
=
'utf-8'
;
private
static
$outer
=
''
;
private
static
$outerAttribut
= [];
private
static
$singleOuter
=
''
;
private
static
$singleOuterAttribut
= [];
private
static
$defaultSingleOuter
=
'item'
;
public
function
A2XML(
array
$data
)
{
$xml
=
new
\XMLWriter();
$this
->begin(
$xml
);
if
(
is_numeric
(current(
array_keys
(
$data
)))) {
foreach
(
$data
as
$key
=>
$val
) {
$this
->singleBegin(
$xml
, true);
$this
->writeElement(
$xml
,
$val
);
$this
->singleEnd(
$xml
);
}
}
else
{
$this
->writeElement(
$xml
,
$data
);
}
return
$this
->
end
(
$xml
);
}
private
function
writeElement(\XMLWriter &
$xml
,
$data
)
{
if
(!
is_array
(
$data
)) {
$xml
->writeElement(self::
$defaultSingleOuter
,
$data
);
return
;
}
foreach
(
$data
as
$key
=>
$val
) {
if
(
is_numeric
(
$key
)) {
is_array
(
$val
) &&
$this
->singleBegin(
$xml
);
$this
->writeElement(
$xml
,
$val
);
is_array
(
$val
) &&
$this
->singleEnd(
$xml
);
continue
;
}
if
(
is_array
(
$val
)) {
$xml
->startElement(
$key
);
$this
->writeElement(
$xml
,
$val
);
$xml
->endElement();
continue
;
}
$xml
->writeElement(
$key
,
$val
);
}
}
private
function
begin(\XMLWriter &
$xml
)
{
$xml
->openMemory();
$xml
->startDocument(self::
$version
, self::
$encoding
);
if
(self::
$outer
) {
$xml
->startElement(self::
$outer
);
}
if
(self::
$outerAttribut
) {
foreach
(self::
$outerAttribut
as
$key
=>
$val
) {
$xml
->writeAttribute(
$key
,
$val
);
}
}
}
private
function
end
(\XMLWriter
$xml
)
{
if
(self::
$outer
) {
$xml
->endElement();
}
$xml
->endDocument();
header(
"Content-type: text/xml"
);
return
$xml
->outputMemory(true);
}
private
function
singleBegin(\XMLWriter
$xml
,
$first
= false)
{
if
(
$first
) {
$xml
->startElement(self::
$singleOuter
?: self::
$defaultSingleOuter
);
if
(self::
$singleOuterAttribut
) {
foreach
(self::
$singleOuterAttribut
as
$key
=>
$val
) {
$xml
->writeAttribute(
$key
,
$val
);
}
}
}
else
{
$xml
->startElement(self::
$defaultSingleOuter
);
}
}
private
function
singleEnd(\XMLWriter
$xml
)
{
$xml
->endElement();
}
public
function
setVersion(
$version
= 1.0)
{
self::
$version
=
$version
;
return
$this
;
}
public
function
setEncoding(
$encoding
=
'utf-8'
)
{
self::
$version
=
$encoding
;
return
$this
;
}
public
function
setOuter(
$outer
=
''
)
{
self::
$outer
=
$outer
;
return
$this
;
}
public
function
setOuterAttribut(
array
$outerAttribut
= [])
{
self::
$outerAttribut
=
$outerAttribut
;
return
$this
;
}
public
function
setSingleOuter(
$singleOuter
)
{
self::
$singleOuter
=
$singleOuter
;
return
$this
;
}
public
function
setSingleOuterAttribut(
array
$singleOuterAttribut
= [])
{
self::
$singleOuterAttribut
=
$singleOuterAttribut
;
return
$this
;
}
public
function
setDefaultSingleOuter(
$defaultSingleOuter
)
{
self::
$defaultSingleOuter
=
$defaultSingleOuter
;
return
$this
;
}
}