2013-01-06 26 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