PHP:简单的 HTML DOM 解析器 - 如何获取具有特定内容的元素?
问题描述:
在 PHP 中,我使用的是 Simple HTML DOM Parser 类.
In PHP I'm using the Simple HTML DOM Parser class.
我有一个包含多个 A 标签的 HTML 文件.
I have a HTML file which has multiple A-tags.
现在我需要找到里面有特定文本的标签.
Now I need to find the tag that has a certain text inside.
例如:
$html = "<a id='tag1'>A</a>
<a id='tag2'>B</a>
<a id='tag3'>C</a>
";
$dom = str_get_html($html);
$tag = $dom->find("a[plaintext=B]");
上面的例子不起作用,因为纯文本只能用作属性.
The above example doesn't work, since plaintext can only be used as an attribute.
有什么想法吗?
答
<?php
include("simple_html_dom.php");
$html = "<a id='tag1'>A</a>
<a id='tag2'>B</a>
<a id='tag3'>C</a>
";
$dom = str_get_html($html);
$select = NULL;
foreach($dom->find('a') as $element) {
if ($element->innertext === "B") {
$select = $element;
break;
}
}
?>