如果使用exit()退出嵌套的foreach循环,则完全停止脚本

时间:2012-12-20 15:59:42

标签: php html loops foreach

我正在构建一个wordpress插件,用于学习原因,这是有问题的代码:

// display latest facebook posts
// Init a cURL resource
$ch = curl_init("https://www.facebook.com/feeds/page.php?format=rss20&id=133869316660964");
curl_setopt( $ch, CURLOPT_POST, false );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
// Make facebook think it is being accessed by a browser to avoid compatability issues
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec( $ch );

// instanciate a new xml element
$fb = new SimpleXMLElement($data);
$i = 0; // set the counter for the foreach loop to 0

echo "<ul>"; // begin the UL

foreach ($fb->channel->item as $item) {
    // foreach item within the tree perform this loop twice
    $link = $item->link; // set the link address
    $post = $item->description; // set the post data
    echo "<li>" . $post, ' :::::: ', '<a href="' . 
    $link . '">' . $link, PHP_EOL . "</a></li>";
    $i++;
    if($i == 2){
        exit();
    }
}
echo "</ul>";

然而,当我检查HTML时,我看到了这一点:(最底层的快速片段)

846656&id=133869316660964
</a></li>

这是foreach循环的最后一部分,其中$ i =&lt; 2所以使用exit似乎完全停止了脚本,我说的是否正确或是否还有其他错误?

2 个答案:

答案 0 :(得分:6)

exit();停止执行php。尝试使用break;退出循环

PHP break

答案 1 :(得分:3)

使用中断而非退出

退出终止php脚本的整个执行