-1

So, i have this awesome web crawler code. it gets requested data from the mentioned site and pastes along with link associated with it. (Good Boy)

Now the problem is, how to limit the extracted data to say 5 rows. I tried putting "LIMIT 5" (which we usually do in php sql queries) but it didn't work..

My code goes as follows::

<div class="news-entry">
            <div class="newsblock">
                <div style="clear:both"></div>
                    <h2>
                       <a rel="nofollow" target="_blank" href="http://www.usmle-forums.com/usmle-step-3-forum/">
                            USMLE-Forums :: STEP-3         
                       </a>
                    </h2>
                <ul>
                    <?php
                        function get_datafour($url) {
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_URL,$url);
                        $result=curl_exec($ch);
                        curl_close($ch);
                        return $result;
                        }
                        $returned_content = get_datafour('http://www.usmle-forums.com/usmle-step-3-forum/');
                        $first_step = explode( '<tbody id="threadbits_forum_30">' , $returned_content );
                        $second_step = explode('</tbody>', $first_step[1]);
                        $third_step = explode('<tr>', $second_step[0]);
                        // print_r($third_step);
                        foreach ($third_step as $element) {
                        $child_first = explode( '<td class="alt1"' , $element );
                        $child_second = explode( '</td>' , $child_first[1] );
                        $child_third = explode( '<a href=' , $child_second[0] );
                        $child_fourth = explode( '</a>' , $child_third[1] );
                        $final = "<a href=".$child_fourth[0]."</a></br>";
                    ?>
                    <li target="_blank" class="itemtitle">
                        <span class="item_new"></span><?php echo $final?>
                    </li>
                    <?php
                        }
                    ?>      
                </ul>        
                <div style="clear:both"></div>
            </div>
        </div>

Any Suggestions are Appreciated..

harishk
  • 418
  • 5
  • 21

1 Answers1

1

Break Foreach loop after 5th result

foreach ($third_step as $key=>$element) {
    //Your Logic Here
    if($key==4){
       break;
    }
}

we are using $key==4 because index starts from 0 hope you got it

Manvir Singh
  • 431
  • 4
  • 6