Php 在foreach循环中取一个,而不是全部

Php 在foreach循环中取一个,而不是全部,php,Php,我使用下面的代码使用PHPScraper在id=news的页面上迭代所有div。是否可以只获取它找到的第一个div,以便数组只包含一个条目?我在想,如果可能的话,在foreach循环中只取一个,就像在c myList中一样 $dom = file_get_html('http://localhost/test.html'); //collect all news entries into an array $myArray = array(); if(!empty($dom)) { $

我使用下面的代码使用PHPScraper在id=news的页面上迭代所有div。是否可以只获取它找到的第一个div,以便数组只包含一个条目?我在想,如果可能的话,在foreach循环中只取一个,就像在c myList中一样

$dom = file_get_html('http://localhost/test.html');

//collect all news entries into an array
$myArray = array();
if(!empty($dom)) {
    $divClass = $title = '';

    foreach($dom->find("div[id*=news]") as $divClass) {
中断;语句用于停止循环的进一步处理。因此,如果您直接使用它,那么循环将只执行一次。

您可以在添加第一个div后使用它来停止循环继续

大概是这样的:

foreach($dom->find("div[id*=news]") as $divClass) {
    $myArray[] = $divClass; // Just assuming you're doing something like this
    break;
}
旁注:代码$divClass=$title=;在此之前,循环在您发布的代码中不起任何作用。变量$divClass将在foreach的每次迭代中被完全覆盖。

我猜您正在使用

要仅获取一个元素,只需执行以下操作:


你指的是什么PHPScraper工具?它很可能有一种获取单个元素而不是数组的方法。请不要只发布代码作为答案,还要解释代码的作用以及它如何解决问题。带有解释的答案通常更有帮助,质量更好,更容易吸引选票。
foreach($dom->find("div[id*=news]") as $divClass) {
    $myArray[] = $divClass; // Just assuming you're doing something like this
    break;
}
$firstDiv = $dom->find('div[id*=news]', 0);