简单的html dom:通过匹配标记中的文本来查找元素



我想找到一个没有类或id的特定h4标记。我想通过文本找到h4标记:
正如您在下面看到的,h4标签位于块标签内部,但每个产品的块标签编号不同,例如其中一些没有价格。所以如果我做这个$html->find('block[2]'),如果没有任何价格,它会显示我的颜色
所以我想说h4inner text = 'Price:'是否显示.block标签内的$2,163。好啊

目标HTML:

<div class="article" id="article">
<div class="block">
<h4>First name and last name:</h4>
name name
</div>
<div class="block">
<h4>Price:</h4>
$2,163
<span>(50% off)</span>
</div>
<div class="block">
<h4>Color:</h4>
black,
<span>and white</span>
</div>
<div class="block">
<h4>Date:</h4> 2020
</div>

<div class="block">
<h4>Time:</h4>
<time datetime="12">12 clock</time>
</div>
</div>

我的PHP:

$html = file_get_html("$url");
foreach ($html->find('#article') as $ret) {
foreach ($ret->find('.block') as $pa) {
foreach ($pa->find('h4') as $e) {
if (strpos($e->innerhtml, "Price:") !== FALSE) {
$str = $e->innerhtml;
$price = $str->parent()->innertext;
//$price = $str->plaintext;
echo $price;
}
}
}
}

我想检查<h4>Price:<h4>是否存在,然后显示.block内容而不包括h4。
但我一无所获。
srry用于我的英语

您可以使用如下函数。它在具有articleID的元素中查找具有block类的元素中的任何<h4>,然后检查其文本。如果匹配,它将删除标题并返回块中剩余内容的文本:

function findValue($html, string $key): ?string
{
foreach ($html->find('#article .block h4') as $h4) {
if ($h4->innertext() === "{$key}:") {
$h4 = clone $h4;  // to prevent altering the document
$block = $h4->parent();
$block->removeChild($h4);
return $block->text();
}
}
return null;
}

用法:

echo findValue($html, 'First name and last name'), PHP_EOL;  // name name
echo findValue($html, 'Price'), PHP_EOL;                     // $2,163 (50% off)
echo findValue($html, 'Color'), PHP_EOL;                     // black, and white
echo findValue($html, 'Date'), PHP_EOL;                      // 2020
echo findValue($html, 'Time'), PHP_EOL;                      // 12 clock

相关内容

最新更新