Skip to content
Advertisement

Create array from xml more objects with same name

Is there a way to create an array from xml file that will contain all of the <IMG_ALTERNATIVE> values so I can use them in my other function? The xml looks like this:

<SHOP>
<SHOPITEM>
<ITEM_ID>item id</ITEM_ID>
<SKU>item SKU </SKU>
<PRODUCT>Product name</PRODUCT>
<DESCRIPTION>Item descirption</DESCRIPTION>
<URL>
https://www.itemurl.com/item
</URL>
<IMGURL>
https://www.itemurl.com/itemimg.jpg
</IMGURL>
<IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg2.jpg
</IMG_ALTERNATIVE>
<IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg3.jpg
</IMG_ALTERNATIVE>

I parse the xml this way in php:

foreach ($xml as $item) {
            $data[md5($item->URL->__toString())] = ['item_id' => null,
                                'title' => $item->PRODUCT->__toString(),
                                'text' => $item->DESCRIPTION->__toString(),
                                'item_url' => $item->URL->__toString(),
                                'img_url' => $item->IMG_URL->__toString(),
                                'img_alt' => $item->IMG_ALTERNATIVE->__toString()
                                ];
        }

Advertisement

Answer

use this code

<?php

$xmlstring = "
<xml>
    <SHOP>
        <SHOPITEM>
            <ITEM_ID>item id</ITEM_ID>
            <SKU>item SKU </SKU>
            <PRODUCT>Product name</PRODUCT>
            <DESCRIPTION>Item descirption</DESCRIPTION>
            <URL>
https://www.itemurl.com/item
</URL>
            <IMGURL>
https://www.itemurl.com/itemimg.jpg
</IMGURL>
            <IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg2.jpg
</IMG_ALTERNATIVE>
            <IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg3.jpg
</IMG_ALTERNATIVE>
        </SHOPITEM>
    </SHOP>
</xml>
";
$array = array();
$xml = new SimpleXMLElement($xmlstring);
foreach ($xml->SHOP->SHOPITEM as $element) {
    foreach($element as $key => $val) {
        array_push ( $array,"{$key}: {$val}");
    }
}
print_r($array);

https://3v4l.org/0igDF

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement