SimpleXMLElement addChild doesn't work in foreach

109 views Asked by At

here is the code:

$icmlData = file_get_contents($config['icml']);

$xmlIter = new SimpleXMLElement($icmlData);

foreach ($xmlIter->shop->offers->offer as $offer) {
    $id = $offer->attributes()['id'];
    $id = strval($id);

    $offer->addChild('externalId', $id);
    $offer->addChild('xmlId', $id);
}

$result = file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'icml_t.xml', $xmlIter->asXML());

I take xml from one file, try to add 2 children to each 'offer' tags and put this xml into another file, but as a result I see two identical files.

Need help.

1

There are 1 answers

0
admhome On

So, I don’t know how correct it is, but also the code change helped solve the problem:

$icmlData = file_get_contents($config['icml']);

$xmlIter = new SimpleXMLElement($icmlData);

$i = 0;

foreach ($xmlIter->shop->offers->offer as $offer) {
    $id = $offer->attributes()['id'];
    $id = strval($id);

    $xmlIter->shop->offers->offer[$i]->addChild('externalId', $id);
    $xmlIter->shop->offers->offer[$i]->addChild('xmlId', $id);

    $i++;
}

$result = file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'icml_t.xml', $xmlIter->asXML());