Php 回显特定类的所有段落

Php 回显特定类的所有段落,php,html,domdocument,getelementsbytagname,getattribute,Php,Html,Domdocument,Getelementsbytagname,Getattribute,有没有一种方法(用PHP)回显属于特定类的(HTML页面的)所有段落?我尝试过类似的方法,但没有效果(没有任何回音) $dom=新的DOMDocument; $dom->loadHTML($html)//我需要的代码包含在$html变量中 foreach($dom->getElementsByTagName('p')作为$段落){ 如果($paragration->getAttribute('class')='items')){ echo$段落->节点值。“”; } } 为了备份Ghost提到

有没有一种方法(用PHP)回显属于特定类的(HTML页面的)所有段落?我尝试过类似的方法,但没有效果(没有任何回音)

$dom=新的DOMDocument;
$dom->loadHTML($html)//我需要的代码包含在$html变量中
foreach($dom->getElementsByTagName('p')作为$段落){
如果($paragration->getAttribute('class')='items')){
echo$段落->节点值。“
”; } }
为了备份Ghost提到的内容,如果您有多个类,最好使用strpos。以此为例,

<?php

$html = "<p class='items two small-font'>This is paragraph 1</p> <br> <hr> <p class='items'>This is paragraph 2</p> <br> <hr> <p class='noitem'>This is paragraph 3</p> <br> <hr>";

$dom = new DOMDocument;
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('p') as $paragraph) {

    $class = $paragraph->getAttribute('class');

    if ( strpos( $class , 'items') !== false ) {
        echo $paragraph->nodeValue."<br>";
    }

} 

?>

请注意,这与
class=“items small font center”
不匹配,只需使用
strpos
而不是可能的重复项
<?php

$html = "<p class='items two small-font'>This is paragraph 1</p> <br> <hr> <p class='items'>This is paragraph 2</p> <br> <hr> <p class='noitem'>This is paragraph 3</p> <br> <hr>";

$dom = new DOMDocument;
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('p') as $paragraph) {

    $class = $paragraph->getAttribute('class');

    if ( strpos( $class , 'items') !== false ) {
        echo $paragraph->nodeValue."<br>";
    }

} 

?>