【问题标题】:Using DOMDocument to extract from HTML document by class使用 DOMDocument 按类从 HTML 文档中提取
【发布时间】:2011-02-25 19:40:33
【问题描述】:

在 DOMDocument 类中,有一些方法可以通过 id 和标签名称(getElementById 和 getElementsByTagName)获取元素,但不能通过类。有没有办法做到这一点?

例如,如何从以下标记中选择 div?

<html>
...
<body>
...
<div class="foo">
...
</div>
...
</body>
</html>

【问题讨论】:

标签: php domdocument


【解决方案1】:

简单的答案是使用 xpath:

$dom = new DomDocument();
$dom->loadHtml($html);
$xpath = new DomXpath($dom);
$div = $xpath->query('//*[@class="foo"]')->item(0);

但这不接受空格。因此,要按空格分隔的类进行选择,请使用以下查询:

//*[contains(concat(' ', normalize-space(@class), ' '), ' class ')

【讨论】:

  • 使用 table[contains(@class, '$classname')] 查看我的替代方案
【解决方案2】:
$html = '<html><body><div class="foo">Test</div><div class="foo">ABC</div><div class="foo">Exit</div><div class="bar"></div></body></html>';

$dom = new DOMDocument();
@$dom->loadHtml($html);

$xpath = new DOMXPath($dom);

$allClass = $xpath->query("//@class");
$allClassBar = $xpath->query("//*[@class='bar']");

echo "There are " . $allClass->length . " with a class attribute<br>";

echo "There are " . $allClassBar->length . " with a class attribute of 'bar'<br>";

【讨论】:

    【解决方案3】:

    如果您需要按空格分隔的类选择,除了ircmaxell的答案:

    $dom = new DomDocument();
    $dom->loadHtml($html);
    $xpath = new DomXpath($dom);
    $classname='foo';
    $div = $xpath->query("//table[contains(@class, '$classname')]")->item(0);
    

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2011-12-07
      • 2021-10-22
      • 2011-10-07
      • 2016-09-29
      相关资源
      最近更新 更多