这是我的数组:
这是我的最后一个数组:
$data = [
'domain'=> $xmlDocument->domain,
'FirstDate' => $xmlDocument->dateAttribute->first_date,
'LastDate' => $xmlDocument->dateAttribute->last_date,
'Category' => $xmlDocument->category->name,
'Action' => $xmlDocument->websiteAction->name,
'Source' => $xmlDocument->source->name,
'LogFile' => $xmlDocument->log_file,
'DateAttribute' => [
'Name' => $xmlDocument->dateAttribute->name,
'Place' => $xmlDocument->dateAttribute->dateLocation->name,
'DateFunction' => $xmlDocument->dateAttribute->dateFunction->name
],
'MasterPage' => [
'MasterAttributes' =>[
],
'Container'=>[
'xpath' => $xmlDocument->masterInformation->xpath
],
'NextPage' =>[],
'LinkAttribute'=>[]
],
];
如你所见, MasterAttributes
关键是一个空数组,我想它,并祝。
我曾尝试
$attributes = $xmlDocument->masterInformation->masterAttributes;
foreach($attributes as $attribute) {
$masterAttribute = [
'Attribute' => [
'name' => $attribute->attributeName->name,
'default_value' => $attribute->default_value
]
];
$data['MasterPage'] ['MasterAttributes'][] = $masterAttribute;
}
生成的XML是:
<MasterAttributes>
<item0>
<Attribute>
<name>bathroom</name>
<default_value>This is the default value</default_value>
</Attribute>
</item0>
<item1>
<Attribute>
<name>price</name>
<default_value>vfd</default_value>
</Attribute>
</item1>
<item2>
<Attribute>
<name>bathroom</name>
<default_value>new default value</default_value>
</Attribute>
</item2>
</MasterAttributes>
请检查是否有提取item0, item1, item2
如何删除它们吗?
更新1
从第一个答案后@lowerends
,我得到了这个结果
<MasterAttributes>
<Attribute_0>
<name>bathroom</name>
<default_value>This is the default value</default_value>
</Attribute_0>
<Attribute_1>
<name>price</name>
<default_value>vfd</default_value>
</Attribute_1>
<Attribute_2>
<name>bathroom</name>
<default_value>new default value</default_value>
</Attribute_2>
</MasterAttributes>
非常接近啥子我需要,但我需要Attribute
没有Attribute 0
或Attribute 1
更新2
我生成这样的XML:
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><websiteInformation></websiteInformation>");
$this->array_to_xml($data,$xml);
$xml->asXML("FileName".XmlDocument::find($id)->id.".xml");
其中$data
是finall数组, array_to_xml
函数为:
public function array_to_xml($student_info, &$xml_student_info) {
foreach($student_info as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_student_info->addChild("$key");
$this->array_to_xml($value, $subnode);
}
else{
$subnode = $xml_student_info->addChild("item$key");
$this->array_to_xml($value, $subnode);
}
}
else {
$xml_student_info->addChild("$key",htmlspecialchars("$value"));
}
}
}