PHP:简单的 HTML DOM 解析器 - 如何获取具有特定内容的元素? [英] PHP: Simple HTML DOM Parser - how to get the element which has certain content?

查看:23
本文介绍了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;   
       }
}
?>

这篇关于PHP:简单的 HTML DOM 解析器 - 如何获取具有特定内容的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆