first xml
<response status="ok">
<Product>
<name>blbla</name>
<productGroupPrimary>test2</productGroupPrimary>
<productGroupSecondary>test</productGroupSecondary>
<purchasePrice>18</purchasePrice>
<retailPrice>29</retailPrice>
<status>active</status>
<productCode>0001</productCode>
</Product>
<Product>
...
</Product>
other xml
<response status="ok">
<StockQuantityInfo productCode="0001" quantityOnStock="5"></StockQuantityInfo>
<StockQuantityInfo productCode="dhzh" quantityOnStock="5"></StockQuantityInfo>
...
</response>
now i would like to use php to make the final XML document look like this
<response status="ok">
<Product>
<name>blbla</name>
<productGroupPrimary>test2</productGroupPrimary>
<productGroupSecondary>test</productGroupSecondary>
<purchasePrice>18</purchasePrice>
<retailPrice>29</retailPrice>
<status>active</status>
<productCode>0001</productCode>
<stock>5</stock>
</Product>
<Product>
...
</Product>
</response>
i have no idea how i could do this i am a beginner
I tried that foreach
foreach ($xml2->Product as $item2) {
$koda2=$item2->productCode;
foreach ($xml3->StockQuantityInfo as $item3) {
$koda3=$item3->productCode;
if ($koda2 ==$koda3 ) {
$zaloga=$item3->quantityOnStock;
$Product=$xml2->Product->addChild('zaloga',$zaloga);
}
}
the result is that it doesn’t do anything to me, there’s no change, I have a mistake somewhere, or I’m thinking in the wrong direction
My Answer:
You are on the right track, but there are a few mistakes in your code. Here is the corrected version:
php
// Load the first XML document
$xml1 = simplexml_load_string('
blbla
test2
test
18
29
active
0001
');
// Load the second XML document
$xml2 = simplexml_load_string('
');
// Loop through each Product element in the first XML document
foreach ($xml1->Product as $product) {
$productCode = (string) $product->productCode;
// Find the corresponding StockQuantityInfo element in the second XML document
foreach ($xml2->StockQuantityInfo as $stockInfo) {
if ((string) $stockInfo['productCode'] == $productCode) {
// Add the stock quantity as a new element to the Product element
$product->addChild('stock', (string) $stockInfo['quantityOnStock']);
}
}
}
// Output the final XML document
echo $xml1->asXML();
This code will loop through each Product element in the first XML document and find the corresponding StockQuantityInfo element in the second XML document based on the product code. It will then add the stock quantity as a new element to the Product element. Finally, it will output the final XML document with the added stock element.
Rate this post
4 of 5 based on 8646 votesComments