获取仅具有给定类的元素的DOMNodeList


Get DOMNodeList of elements with only the given class

我正在使用PHP DOMDocument和DomXPath解析第三方HTML页面。我使用以下代码:

$dom = new DOMDocument();
$html = file_get_contents($url);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
$dom->encoding = "UTF-8";
$finder = new DomXPath($dom);

现在有几个元素使用同一个类,但我想针对只使用给定类的元素,例如:

<table class="tbl"></table>
<table class="tbl red"></table>
<table class="tbl large blue"></table>

我使用以下选择器:

$classname = "tbl";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

当然,它可以获取上面给出的所有三个表。有没有一种简单的方法只得到第一个?感谢

是的,有一种方法。

注意,使用XPath查询,您可以通过以下方式访问所需的节点:

$nodes->item(0);

要只选择第一个节点,您必须以这种方式修改您的模式:

$nodes = $finder->query("(//*[contains(@class, '$classname')])[1]");

但要访问所需的节点,您无论如何都需要使用以下语法:

$nodes->item(0);