'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()
                                ];
        }


Solution 1:[1]

thought about using a regular expression ? https://3v4l.org/uatdY

$ls = "<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>";

preg_match_all('/<IMG_ALTERNATIVE>\r?\n(.*)\r?\n<\/IMG_ALTERNATIVE>/', $ls, $matches);
print_r($matches);

result:

Array
(
    [0] => Array
        (
            [0] => <IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg2.jpg
</IMG_ALTERNATIVE>
            [1] => <IMG_ALTERNATIVE>
https://www.itemurl.com/itemimg3.jpg
</IMG_ALTERNATIVE>
        )

    [1] => Array
        (
            [0] => https://www.itemurl.com/itemimg2.jpg
            [1] => https://www.itemurl.com/itemimg3.jpg
        )

)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FatFreddy