【问题标题】:How to fetch text from span (class) using DomDocument如何使用 DomDocument 从跨度(类)中获取文本
【发布时间】:2021-11-29 09:20:07
【问题描述】:

我是 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-parsing domdocument domxpath


    【解决方案1】:

    你快到了。假设你的目标&lt;span&gt;$dom 中的第一个,试试这个:

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

    ; 输出应该是:

    hello world
    

    【讨论】: