使用DOMDocument按类名获取所有元素 [英] Get all elements by class name using DOMDocument

查看:101
本文介绍了使用DOMDocument按类名获取所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎已经回答了无数次,但我仍然似乎无法将所有内容放在一起.

This question seems to have been answered numerous times but i still cant seem to put the pieces together.

我想按名称获取每个类的节点值.例如

I would like to get node value of every class by name. for example

<td class="thename"><strong>32</strong></td>
<td class="thename"><strong>12</strong></td>

我想抓住32和12.我假设这需要某种for循环,但不确定如何实现它.这是我到目前为止所拥有的

i would like to grab the 32 and the 12. I assume this requires for sort of for loop but not sure exactly how to go about implementing it. Here's what i have so far

$domain = "http://domain.com";
$dom = new DOMDocument();

$dom->loadHTMLFile($domain);
$xpath = new DomXpath($dom);
$div = $xpath->query('//*[@class="thename"]')->item(0);
$stuff = $div ->textContent;

echo($stuff);

推荐答案

这是您要寻找的吗?

    $result = array();

    $doc = <<< HTML
    <html>
        <body>
            <div>1
                <span>2</span>
            </div>
            <div>3</div>
            <div>4
                <span class="class1"><strong>5</strong></span>
                <span class="class1"><strong>6</strong></span>
                <span>7</span>
            </div>
        </body>
    </html>
HTML;
    $classname = "class1";
    $domdocument = new DOMDocument();
    $domdocument->loadHTML($doc);
    $a = new DOMXPath($domdocument);
    $spans = $a->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

    for ($i = $spans->length - 1; $i > -1; $i--) {
        $result[] = $spans->item($i)->firstChild->nodeValue;
    }

    echo "<pre>";
    print_r($result);
    exit();

这篇关于使用DOMDocument按类名获取所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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