【问题标题】:How to check if a Simple HTML element does not exist?如何检查简单的 HTML 元素是否不存在?
【发布时间】:2021-06-03 23:19:33
【问题描述】:

SimpleHtmldom 可用于提取类 a[itemprop="item"]

的第一个元素的内容
$html = str_get_html($html); 
$item = $html->find('a[itemprop="item"]', 1)->innertext; 

但是如果这个类不存在,PHP 会抛出错误

试图获取非对象的属性

我该如何解决这个问题?

【问题讨论】:

    标签: php domparser


    【解决方案1】:

    请先检查元素是否存在:

    // Create DOM from URL or file
    $html = str_get_html($html);
    
    if (($html->find('a[itemprop="item"]', 1))) {
    $item = $html->find('a[itemprop="item"]', 1)->innertext; 
    }else{
    $item = "element not exist";
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2023-03-09
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      相关资源
      最近更新 更多