2

我正在尝试使用DOMCrawler 过滤我的html,但如果找到结果,我需要中断。

有可能打破each吗?或者如果我使用
我怎么能得到?还是不可能?$node->text();foreach

HTML:

<table cellspacing="0" cellpadding="0" align="Center" rules="all" border="1">
    <tbody>
    <tr>
        <td>Entity Name</td>
        <td>NV Business ID</td>
        <td>Status</td>
        <td>Type</td>
    </tr>
    <tr>
        <td><a href="">GOOGLE</a></td>
        <td><a href=""></a></td>
        <td><a href="">Expired</a></td>
        <td><a href="">Reserved Name</a></td>
    </tr>
    <tr>
        <td><a href="">GOOGLE INC.</a></td>
        <td><a href="">NV20161275322</a></td>
        <td><a href="">Active</a></td>
        <td><a href="">Foreign Corporation</a>
        </td>
    </tr>
    </tbody>
</table>

PHP:

$client = new Client();
$client->setHeader('User-Agent', "Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15");
$crawler = $client->request('GET', 'http://nvsos.gov/sosentitysearch/');
$form = $crawler->selectButton('Search')->form();
$crawler = $client->submit($form, array(
    'ctl00$MainContent$txtSearchBox' => 'google',
));
if($this->available == false)return;
$crawler->filter('table tr')->each(function (\Symfony\Component\DomCrawler\Crawler $element) {
    $status = $element->filter('td')->eq(2)->text();
    echo $status;
    if ($status == 'Active') {
        $this->available = false;
        break;
    }
});

我想获得状态。然后如果状态等于“活动”,我想打破循环。


好的,现在我想出了一些东西。

$crawler = $crawler->filter('#ctl00_MainContent_objSearchGrid_dgCorpSearchResults');
foreach ($crawler as $i => $content) {
    $crawler = new Crawler($content);
    foreach ($crawler->filter('#ctl00_MainContent_objSearchGrid_dgCorpSearchResults') as $node) {
        $longStatus = $node->nodeValue;
        echo $longStatus;
    }
}

但现在我不知道如何才能获得第三名<td><tr>

4

1 回答 1

3

虽然你不能 break from $crawler->each(),当然你也不能break用来退出函数,并且没有什么可以返回,所以这$crawler->each()将停止迭代,但你仍然有几个选择。

  1. 例外
    退出大多数功能始终是一种选择。
  2. foreach
    当你自己得到它时,你可以从 切换$crawler->each()foreach。但它比你想象的要简单。只需更换
    $crawler->each(function($element) {
       your_code();
    });
    
    foreach($crawler as $content) {
        $element = new Crawler($content);
        your_code();
    }
    
    无需更改代码中的任何内容。你的原始代码变成
    ...
    foreach($crawler->filter('table tr') as $context) {
        $element = new Crawler($content);
        $status = $element->filter('td')->eq(2)->text();
        echo $status;
        if ($status == 'Active') {
            $this->available = false;
            break;
        }
     }
    
    你仍然可以<td><tr>同样的方式获得第三
于 2020-01-12T03:54:31.977 回答