I am not able to get this foreach to loop. It is only returning the first value, lego. How can I make it loop and return both lego and playmobil.
XML
<product product-id="000000000100165001">
<customattributes>
<customattribute attributeid="brand1">lego</customattribute>
<customattribute attributeid="isBulky">false</customattribute>
<customattribute attributeid="isDropShip">false</customattribute>
</customattributes>
</product>
<product product-id="000000000100164001">
<customattributes>
<customattribute attributeid="brand1">playmobil</customattribute>
<customattribute attributeid="isBulky">false</customattribute>
<customattribute attributeid="isDropShip">false</customattribute>
</customattributes>
</product>
PHP
foreach ($xml->product->customattributes->customattribute as $rating) {
switch((string) $rating['attributeid']) { // Get attributes as element indices
case 'brand1':
echo $rating;
break;
}
}
When you access $xml->product->customattributes
, the syntax is short-hand for $xml->product[0]->customattributes
. That is, you're only looping over the <customattribute>
tags from the first product.
If you want to loop over both products and their attributes, you'll need to use two loops:
foreach ($xml->product as $product) {
foreach ($product->customattributes->customattribute as $rating) {
...
See https://eval.in/1045244 for a full example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.