[英]Extract data from XML attribute and loop in foreach
I am not able to get this foreach to loop. 我无法让此foreach循环。 It is only returning the first value, lego. 它只是返回第一个值,乐高。 How can I make it loop and return both lego and playmobil. 我如何使其循环并返回乐高玩具和playmobil。
XML 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 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
. 当您访问$xml->product->customattributes
,语法是$xml->product[0]->customattributes
。 That is, you're only looping over the <customattribute>
tags from the first product. 也就是说,您只循环了第一个产品的<customattribute>
标签。
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 有关完整示例,请参见https://eval.in/1045244
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.