How can I safely check is node empty or not? (Symfony 2 Crawler)

AlOpal19 picture AlOpal19 · Aug 7, 2012 · Viewed 13.1k times · Source

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();
}

Answer

Alexey Tsinya picture Alexey Tsinya · Nov 13, 2016
$marks = $crawler->filter('.PropertyBody')->count()
    ? $crawler->filter('.PropertyBody')->eq(2)->text() 
    : '';