我知道如何在解析 HTML 时根据 id 和标签获取值。但我不知道如何根据classname
. 这是我尝试过的:
$dom = new DOMDocument();
$dom->loadHTML($html);
$data = $dom->getElementsByTagName($identifier);
foreach ($data as $v)
{
$value[] = $v->nodeValue;
}
您刚刚尝试通过标记名获取元素。你需要做的是:-
1.Get all the elements by TagName.
2. Now take the classname from the tagname if exists.
3.Compare the classname wit ur input classname, if exists print that data.
试试这个,对我有用:-
$dom = new DOMDocument();
$dom->loadHTML($html);
$new_data = $dom->getElementsByTagName('*');
$matched = array();
//echo $data->nodeValue;
for ($i = 0; $i < $new_data->length; $i++) {
if (isset($new_data->item($i)->attributes->getNamedItem('class')->nodeValue)) {
$classname = $new_data->item($i)->attributes->getNamedItem('class')->nodeValue;
if ($classname == $identifier) {
$matched[] = $new_data->item($i)->nodeValue;
}
}
}
print_r($matched);