2012-06-16 21 views
0

在PHP中,我使用簡單的HTML DOM解析器類。PHP:簡單的HTML DOM解析器 - 如何獲取具有特定內容的元素?

我有一個HTML文件,它有多個A標籤。

現在我需要找到裏面有特定文本的標籤。

例如:

$html = "<a id='tag1'>A</a> 
     <a id='tag2'>B</a> 
     <a id='tag3'>C</a> 
     "; 

$dom = str_get_html($html); 
$tag = $dom->find("a[plaintext=B]"); 

上面的例子不工作,因爲明文只能用來作爲屬性。

任何想法的?

+0

在正常的XPath中,它將是'a [content()=「B」]'。問題是:simplehtmldom支持這個嗎?正常的'DOM'與'DOMXPath'會... – Wrikken

回答

3
<?php 
include("simple_html_dom.php"); 
$html = "<a id='tag1'>A</a> 
     <a id='tag2'>B</a> 
     <a id='tag3'>C</a> 
     "; 

$dom = str_get_html($html); 
$select = NULL; 
foreach($dom->find('a') as $element) { 
     if ($element->innertext === "B") { 
      $select = $element; 
      break; 
     } 
} 
?> 
+0

這個工作,但需要在1個find()表達式中得到它,因爲我需要使用來自數據庫的表達式創建數百個不同的刮板。 – Dylan

+0

我不認爲有任何其他的方式。或者,您可以更新simple_html_dom.php代碼並添加對其的搜索功能。我不知道它是否會比上面的代碼更高效,除非在內聯網上存在某種散列。 – Bee

0

假設每個具體的文字你正在尋找的地圖只有一個鏈接(這聽起來像你這樣做),你可以建立一個聯合查找陣列。我只是自己遇到了這個需求。這是我如何處理它。這樣你就不需要每次循環所有的鏈接。

function populateOutlines($htmlOutlines) 
{ 
    $marker = "courses"; 
    $charSlashFwd = "/"; 

    $outlines = array(); 

    foreach ($htmlOutlines->find("a") as $element) 
    { 
    // filter links for ones with certain markers if required 
    if (strpos($element->href, $marker) !== false) 
    { 
     // construct the key the way you need it 
     $dir = explode($charSlashFwd, $element->href); 
     $code = preg_replace(
     "/[^a-zA-Z0-9 ]/", "", strtoupper(
      $dir[1]." ".$dir[2])); 

     // insert the lookup entry 
     $outlines[$code] = $element->href; 
    } 
    } 

    return $outlines; 
} 

// ...stuff... 

$htmlOutlines = file_get_html($urlOutlines); 
$outlines = populateOutlines($htmlOutlines); 

// ...more stuff... 

if (array_key_exists($code, $outlines)) { 
    $outline = $outlines[$code]; 
} else { 
    $outline = "n/a"; 
} 
相關問題