不使用foreach就无法获得明文

问题描述 投票:0回答:2

我正在尝试使用simple_html_dom来获取一个HTML元素的明文('THIS TEXT'):

<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循环(因为它只是一个元素)。

P.S:我一直在尝试这个:

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

var_dump-ing导致NULL。我也试过这个:

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

var_dump-ing导致:

注意:尝试在第19行的C:\ xampp \ htdocs \ curl \ index.php中获取非对象的属性“明文”

我也阅读了文档,但我似乎无法弄清楚这个:(。有人可以帮助我或者至少指出我正确的方向吗?: - -s

谢谢!:D

php simple-html-dom
2个回答
1
投票

你正在使用一个非常古老的图书馆,但它看起来像一个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;

1
投票

问题中的<span>没有child css类,所以你的选择器不正确。此外,您似乎忽略了在调用find时,子项索引为零的要点。试试这个:

$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;
© www.soinside.com 2019 - 2024. All rights reserved.