PHP:按类名获取元素

时间:2017-04-01 02:47:55

标签: php simple-html-dom

<html>
<body>

<p class="class1" id="id1"  > some data 1</p>
<p class="class1" id="id2"  > some data 2</p>
<p class="class1" id="id3"  > some data 3</p>

</body>
</html>

就像在javascript下面代码一样可以完成这项工作

var elems=document.getElementsByClassName("class1");

var length = elems.length;

如何在php中执行相同操作以便我可以多次迭代它?

1 个答案:

答案 0 :(得分:2)

PHP code demo

使用XPath://*[@class="class1"]

<?php
$object = new DOMDocument();
$object->loadHTML('<html>
<body>

<p class="class1" id="id1"  > some data 1</p>
<p class="class1" id="id2"  > some data 2</p>
<p class="class1" id="id3"  > some data 3</p>
<p class="class1" id="id3"  > some data 4</p>

</body>
</html>');

$xpath = new DOMXpath($object);
$elements = $xpath->query('//*[@class="class1"]');
$noOfElements=$elements->length;
echo $noOfElements;