How can I safely check is node empty or not? (Symf

2019-03-17 13:12发布

When I try to take some nonexistent content from page I catch this error:

The current node list is empty.
500 Internal Server Error - InvalidArgumentException 

How can I safely check exists this content or not? Here some examples that does not work:

if($crawler->filter('.PropertyBody')->eq(2)->text()){
    // bla bla
}

if(!empty($crawler->filter('.PropertyBody')->eq(2)->text())){
    // bla bla
}
if(($crawler->filter('.PropertyBody')->eq(2)->text()) != null){
    // bla bla
}

THANKS, I helped myself with:

$count = $crawler->filter('.PropertyBody')->count();
if($count > 2){
    $marks = $crawler->filter('.PropertyBody')->eq(2)->text();
}

3条回答
Explosion°爆炸
2楼-- · 2019-03-17 13:55
try {
    $text = $crawler->filter('.PropertyBody')->eq(2)->text();
} catch (\InvalidArgumentException $e) {
    // Handle the current node list is empty..
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-17 14:09
$marks = ($crawler->filter('.PropertyBody')->count()) ? $crawler->filter('.PropertyBody')->eq(2)->text() : '';
查看更多
在下西门庆
4楼-- · 2019-03-17 14:11

Have you tried something like this?

$text = null;
if (!empty($body = $crawler->filter('.PropertyBody'))) {
    if (!empty($node = $body->eq(2))) {
        $text = $node->text();
    }
}

$this->assertContains('yourText', $text);
查看更多
登录 后发表回答