简体   繁体   中英

Handle error simple_html_dom.php

I am trying to figure out, how to handle errors if the #id or .class that is specified is not found using simple_html_dom. I kept getting an error that says "Trying to get property of non-object in C:\\xampp\\htdocs\\index.php on line 11."

include_once 'simple_html_dom.php';

$html = file_get_html($url);
$ret =  $html->find('#myId');

foreach($ret as $elements) {
    foreach($elements->find('iframe') as $link) {
        return  $link->src;
    }
}

If you're looking for iframes under #myId , you can use the combined query

$html->find('#myId iframe')

If you only want to find iframes where the src attribute is set, you can further refine your query thus:

$html->find('#myId iframe[src]')

$html->find(...) returns an array, so check whether the array returned is empty or not:

$iframes = $html->find('#myId iframe[src]');

if (empty($iframes)) {
    echo "No iframes found!\n";
} else {
    echo "Found some iframes with a src attribute!\n";
    // do your stuff here
}

If you want to look at all iframes, not just those with a src attribute, you can use the following code:

$iframes = $html->find('#myId iframe');

if (empty($iframes)) {
    echo "No iframes found!\n";
} else {
    echo "Found some iframes!\n";
    foreach($iframes as $i) {
        // check whether there is a src attribute or not
        if (isset($i->src)) {
            echo "iframe src is " . $i->src . "\n";
        } else {
            echo "iframe has no src attribute.\n";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM