2013-03-27 70 views
0

我有一个HTML字符串来算DIV特定类的如何使用PHP的DOMDocument

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>'; 

我想指望其类名=“引用” 我已经试过

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

股利但$长度给出了div的总数。我如何才能只计算具有class name =“quote”的div。有没有可以做到这一点的PHP Native功能。

回答

2

有似乎没有成为一个本地DOM文档的功能,但它很容易把它写自己:

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; 
0

尝试用

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

其中quote是您要查询

备注

如果您还想过滤R,之前,对于div的,你之前查询的div,然后申请查询我会建议上述

像这样的事情

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