使用exit()从嵌套if中退出foreach循环将完全停止脚本


Exiting foreach loop from nested if using exit() stops script totally

我正在构建一个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 =<2所以使用退出似乎完全停止脚本,我说的是正确的还是有另一个错误导致这一点?

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

PHP打破

使用打破退出

Exit终止整个php脚本的执行