使用SimpleXMLElement
类在这种情况下会非常理想。下面是一个例子:
<?php
function createOutfitXML(){
$xml = new SimpleXMLElement('<outfits></outfits>');
$head = $xml->addChild("head");
$head->addAttribute("uri", "xxx");
$head->addAttribute("c1", "000");
$head->addAttribute("c2", "2");
$head->addAttribute("z", "1");
$outfit = $xml->addChild("outfit", "jeans");
$outfit->addAttribute("color", "red");
$outfit->addAttribute("size", "32");
$xml->asXML(__DIR__ . "/xml.xml");
}
createOutfitXML();
现在,假设你有一个包含要转换为使用上述功能的XML文档的服装列表的数组。以下是如何可能使用功能的工作:
成套装备ARRAY:
<?php
$outfitsArray = [
"jeans" => [
[
"size" => '32',
"color" => 'Dark Blue',
"price" => 120.00,
"brand" => 'Lee',
],
[
"size" => '34',
"color" => 'Black',
"price" => 100.00,
"brand" => 'Sean Jean',
],
[
"size" => '30',
"color" => 'White',
"price" => 150.00,
"brand" => 'Pepe',
],
],
"shoes" => [
[
"size" => '40',
"color" => 'Black',
"price" => 180.00,
"brand" => 'Lee',
],
[
"size" => '44',
"color" => 'Brown',
"price" => 200.00,
"brand" => 'Sean Jean',
],
[
"size" => '42',
"color" => 'Dark Red',
"price" => 240.00,
"brand" => 'Versace',
],
]
];
的算法:
<?php
function createOutfitXML($outfitsArray){
$xml = new SimpleXMLElement('<outfits></outfits>');
$head = $xml->addChild("head");
$head->addAttribute("uri", "xxx");
$head->addAttribute("c1", "000");
$head->addAttribute("c2", "2");
$head->addAttribute("z", "1");
foreach($outfitsArray as $groupName=>$itemData){
foreach($itemData as $k=>$v){
$outfit = $xml->addChild("outfit");
$outfit->addAttribute("group", $groupName);
foreach($v as $key=>$value){
$outfit->addAttribute($key, $value);
}
}
}
$xml->asXML(__DIR__ . "/xml.xml");
}
createOutfitXML($outfitsArray);
上面的代码将创建一个XML文档内容与此类似:
<?xml version="1.0"?>
<outfits>
<head uri="xxx" c1="000" c2="2" z="1"/>
<outfit group="jeans" size="32" color="Dark Blue" price="120" brand="Lee"/>
<outfit group="jeans" size="34" color="Black" price="100" brand="Sean Jean"/>
<outfit group="jeans" size="30" color="White" price="150" brand="Pepe"/>
<outfit group="shoes" size="40" color="Black" price="180" brand="Lee"/>
<outfit group="shoes" size="44" color="Brown" price="200" brand="Sean Jean"/>
<outfit group="shoes" size="42" color="Dark Red" price="240" brand="Versace"/>
</outfits>