2013-03-27 69 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;