我知道在解析HTML时如何根据id和标签获取值。但我不知道如何根据classname
获得价值。这就是我的尝试:
$dom = new DOMDocument();
$dom->loadHTML($html);
$data = $dom->getElementsByTagName($identifier);
foreach ($data as $v)
{
$value[] = $v->nodeValue;
}
答案 0 :(得分:0)
您刚刚尝试按标记名获取元素。你需要做的是: -
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);