有没有办法回应(使用PHP)属于特定类的所有段落(HTML页面)?我尝试过这样的东西,但它不起作用(它没有回应任何东西)
$dom = new DOMDocument;
$dom->loadHTML($html); //the code I need is contained in the $html variable
foreach($dom->getElementsByTagName('p') as $paragraph) {
if ( $paragraph->getAttribute('class') === 'items') {
echo $paragraph->nodeValue."<br>";
}
}
答案 0 :(得分:1)
备份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>";
}
}
?>