PHP Goutte - Check if an attribute exists before referencing it

Viewed 327

I have the following code to get the urls of images from a site that I am scraping using the PHP Goutte library.

$gClient = new Client();

$crawler = $gClient->request('GET', 'https://somewebsite.org/somepage');

$results = $crawler->filter(
        '.class_id'
    )->each(function ($node, $i) {

        $node->filter('img')->each(function ($im, $k) {
            if ($im->attr('src')) {
                dump($im->attr('src'));
            }
        });
    });

There is an obvious flaw here that I don't know how to fix, I have to check if the "src" attribute exists before I call it (otherwise I get a Call to a member function attr() on null error), but I don't know how to correct this. I've tried the property_exists function as follows:

if (property_exists($im, 'attr("src")') {
...
}

but I'm not sure if this even is the right way to do this if the property that you are trying to check is a function.. Does anyone know how to avoid the call to null error here?

1 Answers

You may apply try..catch.

try {
    echo $im->attr('src');
} catch (InvalidArgumentException $e) {
    echo "No 'src' found";
}
Related