如何使用PHP DOMDocument计算特定类的div

时间:2013-03-27 07:53:29

标签: php domdocument

我有一个html字符串

html_string = '<div class="quote" post_id="48" 
style="border:1px solid #000;padding:15px;margin:15px;" user_id="1"
user_name="rashidfarooq">This is not True</div>

<div class="quote" post_id="49" style="border:1px 
solid #000;padding:15px;margin:15px;" user_id="1" 
user_name="rashidfarooq">This is good for me</div>

<div class="genuine" post_id="49" style="border:1px 
solid #000;padding:15px;margin:15px;" user_id="1" 
user_name="rashidfarooq">This is good for me</div>';

我想计算具有类名=“引用”的div 我试过了

    $dom = new DOMDocument;
    $dom->loadHTML($html_string);
    $divs = $dom->getElementsByTagName('div');
    $length = $divs->length;

但是$ length给出了div的总数。我怎样才能只计算具有类名=“引用”的div。是否有任何PHP Native功能可以做到这一点。

2 个答案:

答案 0 :(得分:2)

似乎没有原生的domdocument功能,但它很容易自己编写:

function getElementsByClassName($elements, $className) {
    $matches = array();
    foreach($elements as $element) {
        if (!$element->hasAttribute('class')) {
            continue;
        }
        $classes = preg_split('/\s+/', $element->getAttribute('class'));
        if ( ! in_array($className, $classes)) {
            continue;
        }
        $matches[] = $element;
    }
    return $matches;
}

$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = getElementsByClassName($dom->getElementsByTagName('div'), 'quote');
$length = $divs->length;

答案 1 :(得分:0)

尝试

$DOMResponse = new \DOMDocument();
$DOMResponse->loadXML($data);
$xpath = new \DOMXPath($DOMResponse);
$length = $xpath->query('/*[@class="quote"]')->length; 

其中quote是您要查询的类

注意

如果您还要在div之前进行过滤,则必须先查询div,然后应用我上面建议的查询

像这样的东西

$length = $xpath->query('//div[@class="quote"]')->length;