如何使用 DomDocument 从 span(类)获取文本

How to fetch text from span (class) using DomDocument

提问人:shakky 提问时间:10/10/2021 最后编辑:shakky 更新时间:10/10/2021 访问量:354

问:

我是 domdocument 的新手。我正在尝试从属于特定类的 span 标签中获取纯文本或内部文本

例如

<span class="test">hello world</span> // Need to retrieve hello world text 

这就是我到目前为止所做的

$dom = new domDocument;
@ $dom->loadHTML($url);
$classname="test";
$finder = new DomXPath($dom);
$spaner = $finder->query("//span[contains(@class, '$classname')]"); // this returns  [length] => 2 which means two classes present with the name of "test", I need to fetch the first one
php html 解析 domdocument domxpath

评论


答:

1赞 Jack Fleeting 10/10/2021 #1

你快到了。假设您的目标是 中的第一个,请尝试以下操作:<span>$dom

$spaner = $finder->query("//span[contains(@class, '$classname')][1]");
echo $spaner[0]->textContent

; 输出应为:

hello world