簡體   English   中英

PHP的DOMDocument檢查跨度類

[英]php domdocument check span class

如何迭代所有標記並檢查類是font18還是font17?

 $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>

非常感謝。

您的HTML會給Input is not proper UTF-8, indicate encoding ! Bytes: 0xE0 0x20 0x6D 0x65錯誤信息,提示Input is not proper UTF-8, indicate encoding ! Bytes: 0xE0 0x20 0x6D 0x65 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 />";
    }
}

以下將遍歷所有span標簽,您可以使用它來檢查類(如果您提供的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選擇所需的元素

如果只想選擇具有font17font18類的元素,則可以將查詢更改為:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM