Atul Sharma
Atul Sharma

Reputation: 10720

PHP script stops execution if unable to read children of element inside try

I'm trying to read html element

 try{
    $contact = trim($wrapper->children(1)->children(1)->children(1)->children(0)->innertext);
}catch(Exception $e){
    echo "Some Error";
}

Now script works normally if $wrapper has children. But, if $wrapper dosen't have children script stops giving the following error.

<b>Fatal error</b>:  Call to a member function children() on a non-object in <b>C:\path\sc.php</b> on line <b>30</b><br />

but, as try catch is their its not expected to stop.

I need to continue the script executing, even if children is not found.

Upvotes: 0

Views: 19

Answers (1)

Blue
Blue

Reputation: 22911

You cannot catch fatal errors in PHP (You can register a shutdown function, but execution will still be stopped). You will need to make some checks to ensure that the children exist.

var $child1 = $wrapper->children(1);

if ( !is_object($child1) )
    return;

var $child2 = $child1->children(1);
...

Alternatively, you can ignore the exception by adding a preceding '@':

$contact = @$wrapper->children(1)->children(1)->children(1)->children(0)->innertext;

Upvotes: 1

Related Questions