2013-01-06 29 views
0

如何迭代所有標記並檢查類是font18還是font17?php domdocument check span class

$html = new DOMDocument(); 
    $html->load('file.html'); 

HTML:

<p><a name="bookmark7"></a><span class="font18" style="font-weight:bold;">Abilitazione</span></p> 
<p><span class="font17">I medici devono essere autorizzati dallo Stato a praticare la loro professione. I requisiti per ottenere questa autorizzazione variano a seconda delle diverse Nazioni. I laureati presso Facoltà mediche estere possono ottenere l'autorizzazione a esercitare in Italia se rispondono ai requisiti statali per quanto riguarda il tirocinio e se superano l'esame di Stato. Nell'ambito della CEE si tratta tuttora di una questione da definire nei particolari.</span></p> 

非常感謝。

+1

你是什麼意思「檢查」據我所看到的,你有一個或其他元素。你想*檢查*如果每個元素都有一個?或者你想要一個或另一個元素的數組?或者,也許可以統計每個班的所有時間?你想要什麼,你嘗試過什麼? –

+1

http://php.net/manual/en/domdocument.getelementsbytagname.php – Supericy

回答

2

通過所有span標籤的follwing將循環,你可以用它來檢查類(如HTML片段,你提供的確實是您正在使用的一個):

$doc = new DOMDocument(); 
libxml_use_internal_errors(true); 
$doc->load('file.html'); 

$xpath = new DOMXPath($doc); 
$nodes = $xpath->query('//span'); 

foreach ($nodes as $node) { 
    echo $node->getAttribute('class'); 
} 

演示:http://codepad.viper-7.com/pQuQw1

如果HTML實際上不同,你可以告訴我,所以我可以改變我的代碼片段。僅在xpath查詢中選擇特定元素也是值得的(例如,僅選擇具有類font17font18的元素)。

請注意,我用DOMXPath,因爲這會給你更多的靈活性,以更改查詢,選擇你需要根據你的HTML

的元素如果你只需要選擇與font17類或元素font18你可以查詢更改爲類似:

$nodes = $xpath->query('//span[contains(@class, "font17")]|//span[contains(@class, "font18")]'); 

演示:http://codepad.viper-7.com/mHo5P7

+0

+總是很優雅 – Baba

3

你的HTML會給錯誤的Input is not proper UTF-8, indicate encoding ! Bytes: 0xE0 0x20 0x6D 0x65如果使用$doc->load("file.html");這裏有一個簡單的解決辦法

$doc = new DOMDocument('1.0', 'UTF-8'); 
libxml_use_internal_errors(true); 
$doc->loadHTML(file_get_contents("file.html")); 

foreach ($doc->getElementsByTagName('span') as $node) { 
    if (preg_match("/^font1[7|8]$/", $node->getAttribute('class'))) { 
     echo $node->nodeValue, "<br /><br />"; 
    } 
} 
+1

有一個upvote陛下。 ;) – PeeHaa