[英]Extract data from XML attribute and loop in foreach
我無法讓此foreach循環。 它只是返回第一個值,樂高。 我如何使其循環並返回樂高玩具和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;
}
}
當您訪問$xml->product->customattributes
,語法是$xml->product[0]->customattributes
。 也就是說,您只循環了第一個產品的<customattribute>
標簽。
如果要循環兩種產品及其屬性上,你需要使用兩個循環:
foreach ($xml->product as $product) {
foreach ($product->customattributes->customattribute as $rating) {
...
有關完整示例,請參見https://eval.in/1045244
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.