<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中执行相同操作以便我可以多次迭代它?
答案 0 :(得分:2)
使用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;