使用HTML中的类名获取标记的值

时间:2013-03-06 07:23:46

标签: php html

我知道在解析HTML时如何根据id和标签获取值。但我不知道如何根据classname获得价值。这就是我的尝试:

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

$data = $dom->getElementsByTagName($identifier);

foreach ($data as $v) 
{
    $value[] = $v->nodeValue;
}

1 个答案:

答案 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);