这是我的view
我的代码:
$xml = new DOMDocument("1.0", "UTF-8");
$dateAdded = $xml->createElement("DATE_ADDED", date('Y-m-d H:i:s'));
$dateAdded = $xml->appendChild($dateAdded);
$shop = $xml->createElement("SHOP");
$shop = $xml->appendChild($shop);
foreach ($post as $key => $value) {
foreach ($products as $product) {
$shopproduct = $xml->createElement("SHOPPRODUCT");
$test = $xml->createElement($key, $product[$key]);
$test = $shopproduct->appendChild($test);
$shopproduct = $shop->appendChild($shopproduct);
}
}
$xml->save('test.xml');
变量$post
如下所示:
array(2) {
["product_id"]=>
string(1) "1"
["name"]=>
string(1) "1"
}
变量$products
如下所示:
array(2 {
[0] =>
array(2) {
["product_id"] =>
string(2) "30"
["name"] =>
string(12) "Canon EOS 5D"
}
[1] =>
array(2) {
["product_id"] =>
string(2) "47"
["name"]=>
string(9) "HP LP3065"
}
}
代码(XML文件)的结果如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<DATE_ADDED>2017-06-26 11:52:59</DATE_ADDED>
<SHOP>
<SHOPPRODUCT>
<product_id>30</product_id>
</SHOPPRODUCT>
<SHOPPRODUCT>
<product_id>47</product_id>
</SHOPPRODUCT>
<SHOPPRODUCT>
<name>Canon EOS 5D</name>
</SHOPPRODUCT>
<SHOPPRODUCT>
<name>HP LP3065</name>
</SHOPPRODUCT>
</SHOP>
如何让它看起来像这样?
<?xml version="1.0" encoding="UTF-8"?>
<DATE_ADDED>2017-06-26 11:52:59</DATE_ADDED>
<SHOP>
<SHOPPRODUCT>
<product_id>30</product_id>
<name>Canon EOS 5D</name>
</SHOPPRODUCT>
<SHOPPRODUCT>
<product_id>47</product_id>
<name>HP LP3065</name>
</SHOPPRODUCT>
</SHOP>
答案 0 :(得分:1)
根据您的变量,您应首先迭代$products
并在$post
秒后迭代:
foreach ($products as $product) {
$shopproduct = $xml->createElement("SHOPPRODUCT");
foreach ($post as $key => $value) {
$test = $xml->createElement($key, $product[$key]);
$test = $shopproduct->appendChild($test);
$shopproduct = $shop->appendChild($shopproduct);
}
}