douyi5157 2014-07-27 16:12
浏览 52
已采纳

回声出第一个foreach数组

I am using this piece of code with using Simple Html dom :

$google = "http://www.google.com/something.";

 $html = file_get_html($google_html);

 foreach ($html->find('span[class=st]') as $element) 

    echo $element->innertext;

But i just want to echo out the first one of $element->innertext.

How can i just echo out first one ?

The above code echo's all elements.

  • Is there any way to stop the searching of simpledom , when the first child of array get found ?

I mean we don't need to get ALL of the elements, we just need the first one, so it's wasting time to picking all elements and them picking up the first one !

the Better is that when the fist one , got found , the SimpleDom get stop for finding new items.

  • 写回答

2条回答 默认 最新

  • duandai2178 2014-07-27 16:14
    关注

    Use break() after the first iteration.

    foreach ($html->find('span[class=st]') as $element){
        echo $element->innertext;
        break;
    }
    

    You can read more about break() in this documentation from PHP.net: http://php.net/manual/en/control-structures.break.php


    But I'd use this method to get the first element of the array instead:

    echo $html->find('span[class=st]')->innertext;
    

    No need to loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?