例如我有一个数组
Array ( [0] => car [1] => bmw [2] => colour [3] => red [4] => quality [5] => good)
我也有一门课,将数组复制到 xml。
它像这样将数组复制到xml
<root>
<0>car</0>
<1>bmw</1>
<2>colour</2>
<3>red</3>
<4>quality</4>
<5>good</5>
</root>
我需要像这样将数组复制到xml
<root>
<car>bmw</car>
<colour>red</colour>
<quality>good</quality>
</root>
我的课
class Array2XML {
private $writer;
private $version = '1.0';
private $encoding = 'UTF-8';
private $rootName = 'root';
function __construct() {
$this->writer = new XMLWriter();
}
public function convert($data) {
$this->writer->openMemory();
$this->writer->startDocument($this->version, $this->encoding);
$this->writer->startElement($this->rootName);
if (is_array($data)) {
$this->getXML($data);
}
$this->writer->endElement();
return $this->writer->outputMemory();
}
public function setVersion($version) {
$this->version = $version;
}
public function setEncoding($encoding) {
$this->encoding = $encoding;
}
public function setRootName($rootName) {
$this->rootName = $rootName;
}
private function getXML($data) {
foreach ($data as $key => $val) {
if (is_numeric($key)) {
$key = 'key'.$key;
}
if (is_array($val)) {
$this->writer->startElement($key);
$this->getXML($val);
$this->writer->endElement();
}
else {
$this->writer->writeElement($key, $val);
}
}
}
}