档案1
<?xml version="1.0" encoding="utf-8"?>
<urunler>
<urun>
<urunkod>2296</urunkod>
<urunadi><![CDATA[Nuk Kauçuk Emzik No.3 (18+ Ay) -Fun-]]></urunadi>
<desi>1</desi>
<stok>113</stok>
<satis>5.46</satis>
</urun>
</urunler>
文件2
<urunler>
<urun id="2296" secenekid="4" grup="YAS;" ozellik="1" fiyat="0" agirlik="0" Stok="0"/>
<urun id="2296" secenekid="5" grup="YAS;" ozellik="2" fiyat="0" agirlik="0" Stok="0"/>
</urunler>
我想得到:
<?xml version="1.0" encoding="utf-8"?>
<urunler>
<urun>
<urunkod>2296</urunkod>
<urunadi><![CDATA[Nuk Kauçuk Emzik No.3 (18+ Ay) -Fun-]]></urunadi>
<desi>1</desi>
<stok>113</stok>
<satis>5.46</satis>
<options>
<option>
<urunid>2296</urunid>
<grup>YAS</grup>
<ozellik>1</ozellik>
<stok>0</stok>
</option>
<option>
<urunid>2296</urunid>
<grup>YAS</grup>
<ozellik>2</ozellik>
<stok>0</stok>
</option>
</options>
</urun>
</urunler>
答案 0 :(得分:0)
对于这种情况,您似乎需要有关排序算法逻辑的帮助,我可以尝试帮助您。
首先,您需要将xml内容分配给第一个xml文件中的某个php变量:
$file_1 = simplexml_load_file("file_1.xml") or die("Error:
Cannot create object";
现在你必须解析第二个xml文件以获取每个id的所有属性,并将你的选项收集为辅助数组:
$options = array();
$file_2 = simplexml_load_file("file_2.xml") or die("Error: Cannot create object");
foreach ($file_2->urunler->urun as $urun_2) {
$id = $urun_2('id');
$grup = $urun_2('grup'); // you may apply some filter here
$ozellik = $urun_2('ozellik');
$stok = $urun_2('stok');
array_push($options, array(
'id' => $id,
'grup' => $grup,
'ozellik' => $ozellik,
'stok' => $stok
);
}
现在,您可以通过使用id比较的多个foreach循环将子节点添加到第一个xml文件中:
foreach ($file_1->urunler->urun as $urun_1) { // for each node from file 1
foreach ($options as $option) { // for each option from your helper collection
if ($urun_1->urunkod == $option['id']) { // if id from some of your option is equal to the current node from the file 1
if ($urun_1->options == null) { // add options node if not exist
$urun_1->addChild("options");
}
$option = $urun_1->options->addChild("option");
$option->addChild("urunid");
$option->addChild("grup");
$option->addChild("ozellik");
$option->addChild("stok");
$option->urunid = $option['id'];
$option->grup = $option['grup'];
$option->ozellik = $option['ozellik'];
$option->stok = $option['stok'];
}
}
}
$file_1->save('file_1_v2.xml');‘
对您也有帮助:如何在php https://www.w3schools.com/php/php_xml_simplexml_get.asp
中使用简单的xml