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()
];
}
CodePudding user response:
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
)
)
CodePudding user response:
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);