March 7, 2012

How can I exclude first <tr>

Question by mustafa

With php dom, I am getting all TRs and TDs inside.

<?PHP
foreach($table->getElementsByTagName('tr') as $tr){
   echo $tr->getElementsByTagName('td')->item(0)->nodeValue);
}
?>

Can we exclude the first tr and its tds.

Answer by Michael Berkowski

I think the node list is numerically indexed (though I cannot test it), so using a key in the foreach may work:

foreach($table->getElementsByTagName('tr') as $key => $tr){
   // Don't act on the first element
   if ($key > 0) {
     echo $tr->getElementsByTagName('td')->item(0)->nodeValue);
   }
}

Answer by Starx

Compare the index of elements, if its first and use continue the to skip the loop.

<?PHP
foreach($table->getElementsByTagName('tr') as $index => $tr){
   if($index == 0) { continue; }
   echo $tr->getElementsByTagName('td')->item(0)->nodeValue);
}
?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!