PHP SimpleXML repeated data

霸气de小男生 提交于 2019-12-24 10:01:10

问题


Using SimpleXML to pull data from a basic XML file. The XML looks something like:

<shop>
  <section>
    <title></title>
    <products>
      <item>
        ...
      </item>
    </products>
  </section>
</shop>

I can load and loop out the nodes, but when I populate the HTML with each sections items it keeps repeating the first sections items. I'm confused because each section name is outputting correctly but using the first set of items.

foreach($xml->section as $section){
$i=0;
echo '<div class="section"><div class="sectionTop"><h3>'.$section->title.'</h3><a class="expand">+/-</a></div>';         

foreach($xml->section->products as $products){
    foreach($products->item as $item){
        if($i==3){echo '</div><div class="extra">';}?>

        <div class="item">
        <img src="<?=$item->image?>" />
        <div class="prodName"><?=$item->name?></div>
            <div class="price">&pound;<?=$item->price?></div>
        <a href="<?=$item->url?>" class="shopNow">SHOP</a>
    </div>

        <? 
        $i++;
        unset($item);
    }
    unset($products);
}

Can anybody help? This where I am so far, unset doesn't work :( <shop> is $xml


回答1:


You should use $section variable to count it products.

So foreach($xml->section->products as $products){ -> foreach($section->products as $products){



来源:https://stackoverflow.com/questions/6610121/php-simplexml-repeated-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!