XPath选择多个标签

5

我想使用PHP DOMXPath查询来查找多个标签(td和th)。

我该怎么做呢?


你有阅读过DOMXPath的手册吗?http://www.php.net/manual/en/domxpath.query.php - Pankucins
1个回答

7
您可以使用|(并集)运算符。这里是一个例子:
$doc = new DOMDocument();
$doc->loadHTML('<table>
<tr>
<th>table header</th>
<td>table cell</td>
</tr>
</table>');

$xpath = new DOMXPath($doc);

$rows = $xpath->query('//tr');                        // select all <tr> elements anywhere in the document
$cols = $xpath->query('./th | ./td', $rows->item(0)); // select all <th>/<td> from context
                                                      // where context = first row
echo $cols->length;             // 2
echo $cols->item(0)->nodeValue; // table header
echo $cols->item(1)->nodeValue; // table cell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接