I'm provided a XML file with this structure:
<items>
<item>
<images>
<image>A</image>
<image>B</image>
<image>C</image>
</images>
.
.
.
</item>
</items>
However the import function of my Shop requires the following format:
<items>
<item>
<images>
<image>A</image>
<image1>B</image>
<image2>C</image>
</images>
.
.
.
</item>
</items>
At first I was thinking I would do this simply in Java since it would be pretty easy to read line by line and restructure the document but I would love to have it so I can just visit a url and this is done for me.
Here is the approach I took:
<?php
$xml = simplexml_load_file('data.xml');
// Loop over items in original xml
for($i = 0; $i < count($xml->item); $i++)
{
$images;
if( ($c = count($xml->item[$i]->images->image)) > 1)
{
$images = $xml->item[$i]->images;
// Remove entry
unset($xml->item[$i]->images);
$xml->item[$i]->addChild('images');
for($y = 0; $y < count($images->image); $y++)
{
if($y == 0)
{
$xx = $xml->item[$i]->images->addChild('image', $images->image[$y]);
}else {
$xml->item[$i]->images->addChild('image' . $y, $images->image[$y]);
}
}
var_dump($images);
}
}
$xml->asXML('POTO.xml');
The dilemma I have tho is that none of the childs get added to images. I have been told I need to restructure the whole document but this is kind of silly if I var_dump just after removing the images node the node and it's children are all removed however when I go to add images node back to item node it and var_dump the node it shows the node was added to item node as a child however when I try to add image to images nothing gets added.
Do I really need to restructure the whole document because it seems simpler to do it in Java then. Or did I miss something.
count($xml->item)andcount($images->image)? Are your loop bodies executed?SimpleXMLElement::count()object method, but using the basiccount()was actually standard before that. Who knew? Ref: us3.php.net/manual/en/simplexmlelement.count.php