如何检测元素是否存在

时间:2015-02-19 20:36:27

标签: php simple-html-dom

大家好我是通过使用简单的html dom获取数据

这是我的php代码,它从网站获取数据     举出(' simple_html_dom.php&#39);

$html = new simple_html_dom();
$html->load_file($this->main_url.$lin->link);
if($html){
    //check if language heading h2 exist then process forward
    if($html->find('h2.channel-title',0)){
        fetch data from tables
     }
}

当h2.channer-title不存在时,此行if($html->find('h2.channel-title',0))在简单html dom的find函数中找到h2.channel-title会给我一个致命的错误

在许多页面<h2 class="channel-title"> English Links</h2>存在,所以我根据它们编写代码并在我的foreach循环中进一步处理它正常工作并获取所有数据。

但是

<h2 class="channel-title">English Links</h2>标记不存在时,它会给我一个错误

Fatal error: Call to a member function find() on a non-object in C:\xampp\apps\wordpress\htdocs\wp-content\plugins\autobot\engine\simple_html_dom.php on line 1113

请帮助我,我被困在它需要帮助谢谢你。我想如果h2.channel-title存在运行我的foreach代码,否则运行另一个但不要发出错误它停止我的整个脚本。 :(

2 个答案:

答案 0 :(得分:0)

var_dump($html);

您使用的是哪个库?

答案 1 :(得分:0)

这可能有所帮助。

$html = new simple_html_dom();
$html->load_file($this->main_url.$lin->link);

if($html) {
    $var = $html->find('h2.channel-title',0);

    if(isset($var)) {
        fetch data from tables
    } else{
        //do something
    }
}