如果您想尝试另一种方法,请使用Magento \ Framework \ Filesystem \ Io \ File和Magento \ Framework \ Convert \ ConvertArray。ConvertArray用于从多维数组制作xml文件,File可以为您编写该文件(并检查权限,创建目录等)。这是一个基本示例:
public function __construct(
\Magento\Framework\Filesystem\Io\File $file,
\Magento\Framework\Convert\ConvertArray $convertArray
)
{
$this->file = $file;
$this->convertArray = $convertArray;
}
public function createMyXmlFile($assocArray, $rootNodeName, $filename = 'file.xml')
{
// ConvertArray function assocToXml to create SimpleXMLElement
$simpleXmlContents = $this->convertArray->assocToXml($assocArray,rootNodeName);
// convert it to xml using asXML() function
$content = $simpleXmlContents->asXML();
$this->file->write($filename, $contents);
}
如果我的数组是:
$myArray = array(
'fruit' => 'apple',
'vegetables' => array('vegetable_1' => 'carrot', 'vegetable_2' => 'tomato'),
'meat' => 'none',
'sweets' => 'chocolate');
然后调用我的函数:
$simpleXmlContents = $this->convertArray->assocToXml($myArray, 'diner');
$this->file->write($myXmlFile,$simpleXmlContents->asXML());
我将在myfile.xml中得到以下内容:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<diner><fruit>apple</fruit><vegetables><vegetable_1>carrot</vegetable_1>
<vegetable_2>tomato</vegetable_2></vegetables><meat>none</meat>
<sweets>chocolate</sweets></diner>