简体   繁体   中英

php simplexml foreach and while loop

I am using php simplexml and foreach to loop a xml file. the code just like

$xml = simplexml_load_file(myfile.xml);
foreach($xml->contents as $list){
     $name= $list->name;
         $price=$list->price;
         $prob=$list->Price;

    echo $name, $price, $prob;
}

If I have 100 items, how can I insert a class for every 5 items?

the output like

<div id="showup"> 
$name, $price, $prob (1)
$name, $price, $prob (2)
$name, $price, $prob (3)
$name, $price, $prob (4)
$name, $price, $prob (5)
</div>
<div id="showup"> 
$name, $price, $prob (6)
$name, $price, $prob (7)
$name, $price, $prob (8)
$name, $price, $prob (9)
$name, $price, $prob (10)
</div>
...............

Do I have to use while instead of foreach? the advantage for foreach is that, I dont need to count how many items in the xml file. or I can use both

hope someone could help, thanks :-)

try:

<?php $counter = 0; ?>
<div id="showup">
<?php foreach($xml->contents as $list) {

    $name= $list->name;
    $price=$list->price;
    $prob=$list->Price;

   echo $name, $price, $prob;
   $counter++;
   if( $counter % 5 == 0) { 
?>
</div><div id='showup'> 
<?php } } ?>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM