Xpath选择多个标签

时间:2013-03-25 09:18:58

标签: php xpath

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

我该怎么做?

1 个答案:

答案 0 :(得分: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
相关问题