根据这里的答案,我创建了一个Github仓库https://github.com/jmarceli/array2xml。
可能不是最美观的仓库,但代码似乎运行良好。
以下是可用的代码:
class ArrayToXML {
private $version;
private $encoding;
public function __construct($xmlVersion = '1.0', $xmlEncoding = 'UTF-8') {
$this->version = $xmlVersion;
$this->encoding = $xmlEncoding;
}
public function buildXML($data, $startElement = 'data'){
if(!is_array($data)){
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
return false;
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($this->version, $this->encoding);
$xml->startElement($startElement);
$this->writeEl($xml, $data);
$xml->endElement();
return $xml->outputMemory(true);
}
protected function writeAttr(XMLWriter $xml, $data) {
if(is_array($data)) {
$nonAttributes = array();
foreach($data as $key => $val) {
if($key[0] == '@') {
$xml->writeAttribute(substr($key, 1), $val);
} else if($key[0] == '%') {
if(is_array($val)) $nonAttributes = $val;
else $xml->text($val);
} elseif($key[0] == '#') {
if(is_array($val)) $nonAttributes = $val;
else {
$xml->startElement(substr($key, 1));
$xml->writeCData($val);
$xml->endElement();
}
}
else $nonAttributes[$key] = $val;
}
return $nonAttributes;
}
else return $data;
}
protected function writeEl(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value) && !$this->isAssoc($value)) {
foreach($value as $itemValue){
if(is_array($itemValue)) {
$xml->startElement($key);
$itemValue = $this->writeAttr($xml, $itemValue);
$this->writeEl($xml, $itemValue);
$xml->endElement();
} else {
$itemValue = $this->writeAttr($xml, $itemValue);
$xml->writeElement($key, "$itemValue");
}
}
} else if(is_array($value)) {
$xml->startElement($key);
$value = $this->writeAttr($xml, $value);
$this->writeEl($xml, $value);
$xml->endElement();
} else {
$value = $this->writeAttr($xml, $value);
$xml->writeElement($key, "$value");
}
}
}
protected function isAssoc($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
之后,只需使用ArrayToXML
类。例如:
$xml = new ArrayToXML()
print $xml->buildXML($input)
if(is_array($value))
语句之前添加$fKey = is_numeric($key) ? 'numericValue' : $key;
,并且在foreach语句的其余部分中使用$fKey
。 - Vassilisif(is_numeric($key)) { $key = 'node'; }
并将“function write”移至外部,您不能声明两次相同的函数,但@Conrad会知道的。(该死,我现在看到了@disq的评论哈哈) - Wiliam