2015-05-12 33 views
0

我試圖在HTML中找到標記的所有元素並獲取起點和終點。如何使用PHP查找HTML中的所有元素並獲取所有職位?

這裏是我的樣本HTML

some content <iframe></iframe> <iframe></iframe> another content 

這是我迄今爲止代碼了。

$ dom = HtmlDomParser :: str_get_html($ this-> content);

$iframes = array(); 
foreach($dom->find('iframe') as $iframe) { 
    $iframes[] = $iframe; 
} 

return array(
    'hasIFrame' => count($iframes) > 0 
); 

獲取元素的數量是容易的,但我不知道是否HTMLDomParser能得到起點和終點的位置?

我要的是

array( 
'hasIFrame' => true, 
'numberOfElements => 2, 
array ( 
    0 => array (
    'start' => $firstStartingElement, 
    'end' => $firstEndingElement 
), 
    1 => array ( 
    'start' => $secondStartingElement, 
    'end' => $secondEndingElement 
) 
) 
+1

你是什麼意思與開始和結束位置? –

+0

元素在標籤中的位置。 – toy

+0

字符串本身在整個字符串標記中的位置? – Ghost

回答

0

如果你看一下官方的文檔(http://simplehtmldom.sourceforge.net/),你可以很容易地發現了一種存在於你的DOM的多少個元素:

// Find all images 
foreach($html->find('img') as $element) { 
     echo $element->src . '<br>'; 
} 

您只需要檢索$ html-> find('iframe')並驗證其大小以知道是否至少有一次。

+0

我也想要元素的位置。不知道這個lib是否也提供這個功能? – toy

+0

該文檔沒有提供這種類型的功能的任何示例,但您可以通過一些技巧來獲取您想要的內容。如果有辦法檢索並遍歷所有的孩子,那麼你可以扣除一個職位 – Cr3aHal0

0

您可以這樣做:

$html = "some content <iframe></iframe> <iframe></iframe> another content"; 
preg_match_all('/<iframe>/', $html, $iframesStartPositions, PREG_OFFSET_CAPTURE); 
preg_match_all('/<iframe\/>/', $html, $iframesEndPositions, PREG_OFFSET_CAPTURE); 


$iframesPositions = array(); 
foreach($dom->find('iframe') as $key => $iframe) { 
    $iframesPositions[] = array(
     'start' => $iframesStartPositions[0][$key][1], 
     'end' => $iframesEndPositions[0][$key][1] + 9 // 9 is the length of the ending tag <iframe/> 
    ); 
} 

return array(
    'hasIFrame'  => count($iframesPositions) > 0, 
    'numberOfElements' => count($iframesPositions), 
    'positions'  => $iframesPositions 
); 
相關問題