让您自定义 XmlResponseFormatter 并覆盖此函数:
protected function buildXml($element, $data)
{
if (is_array($data)
|| ($data instanceof \Traversable
&& $this->useTraversableAsArray
&& !$data instanceof Arrayable)
) {
foreach ($data as $name => $value) {
if(is_array($value) && $this->checkArrayKeyNumber($value)){
foreach ($value as $number => $childValue) {
$ele = new DOMElement($name);
$element->insertBefore(
$element->ownerDocument->createTextNode("\n")
);
$element->appendChild($ele);
$this->buildXml($ele, $childValue);
}
continue;
}
if (is_int($name) && is_object($value)) {
$this->buildXml($element, $value);
} elseif (is_array($value) || is_object($value)) {
$child = new DOMElement($this->getValidXmlElementName($name));
$element->insertBefore(
$element->ownerDocument->createTextNode("\n")
);
$element->appendChild($child);
$this->buildXml($child, $value);
} else {
$child = new DOMElement($this->getValidXmlElementName($name));
$element->insertBefore(
$element->ownerDocument->createTextNode("\n")
);
$element->appendChild($child);
$child->appendChild(
new DOMText($this->formatScalarValue($value))
);
}
}
} elseif (is_object($data)) {
if ($this->useObjectTags) {
$child = new DOMElement(StringHelper::basename(get_class($data)));
$element->appendChild($child);
} else {
$child = $element;
}
if ($data instanceof Arrayable) {
$this->buildXml($child, $data->toArray());
} else {
$array = [];
foreach ($data as $name => $value) {
$array[$name] = $value;
}
$this->buildXml($child, $array);
}
} else {
$element->appendChild(new DOMText($this->formatScalarValue($data)));
}
$element->insertBefore(
$element->ownerDocument->createTextNode("\n")
);
}
添加新函数以检查您的数组数据的键是数字的位置,例如
[
'days' =>
[
0 => 'd1',
1 => 'd2'
]
]
这个函数
private function checkArrayKeyNumber($array)
{
$keys = array_keys($array);
$numeric = true;
foreach ($keys as $key) {
if(!is_numeric($key)){
$numeric = false;
}
}
return $numeric;
}
最后,添加到您的自定义响应类 init()
public function init()
{
parent::init();
$this->formatters['xml']
= 'path\to\your\custom\XmlResponseFormatter';
}