代码之家  ›  专栏  ›  技术社区  ›  emma

不使用foreach就无法获取明文

  •  0
  • emma  · 技术社区  · 7 年前

    我试着用 simple_html_dom

    <div class="parent">
        <span><i class="fa fa-awesome"></i>THIS TEXT</span>
    </div>
    

    foreach($html->find('div.parent span.child') as $text){
        echo $text->plaintext;
    }
    

    但它只是一个元素,我正在寻找一种不使用 foreach 循环(因为它只是一个元素)。

    $html->find('div.parent span.child', 1);
    

    但是 var_dump -结果是 NULL . 我也试过这个:

    $html->find('div.delivery-status span.status', 1)->plaintext;
    

    但是 变量转储

    注意:正在尝试获取中非对象的属性“明文”

    我也阅读了文档,但我似乎无法理解这一点:(。有人能帮我一下吗,或者至少给我指个方向好吗?:-s公司

    谢谢您!:D个

    2 回复  |  直到 7 年前
        1
  •  1
  •   miken32 Amit D    7 年前

    foreach 循环是作者希望它如何工作的。这对于返回大多数函数的节点列表的DOM函数来说是典型的。环路怎么了?您也可以在普通的旧PHP中执行此操作:

    $html = <<< HTML
    <div class="parent">
        <span><i class="fa fa-awesome"></i>THIS TEXT</span>
    </div>
    HTML;
    $dom = new \DomDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    $xpath = new \DOMXPath($dom);
    $data = $xpath->query("//div[@class='parent']/span/text()");
    echo $data[0]->textContent;
    
        2
  •  1
  •   Nima    7 年前

    <span> child css类,因此您的选择器不正确。另外,调用find时,children的索引是以零为基础的,这一点您似乎没有注意到。试试这个:

    $str = '<div class="parent"><span><i class="fa fa-awesome"></i>THIS TEXT</span></div>';
    $html = str_get_html($str);
    
    // no .child for the span, and 0 as the index of target child
    print $html->find('div.parent span', 0)->plaintext;
    
    推荐文章