处理错误simple_html_dom.php

时间:2014-08-25 20:50:11

标签: php class error-handling

我试图找出,如果使用simple_html_dom找不到指定的#id或.class,如何处理错误。我一直收到一条错误,上面写着“试图在第11行的C:\ xampp \ htdocs \ index.php中获取非对象的属性”。

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

1 个答案:

答案 0 :(得分:0)

如果您在#myId下查找iframe,则可以使用合并查询

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

如果您只想查找设置了src属性的iframe,则可以进一步细化您的查询:

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

$html->find(...)返回一个数组,因此请检查返回的数组是否为空:

$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
}

如果您想查看所有iframe,而不仅仅是那些src属性的iframe,您可以使用以下代码:

$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";
        }
    }
}
相关问题