HTML DOMDocument从段落后面的标签中获取字符串

时间:2013-10-14 20:05:14

标签: php html domdocument

我想解析html文档。我需要'h2'之后所有'p'的内容。

要解析的html :(示例)

<h1>Lorem ipsum</h1>
<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, 
</p>

<h2>Aenean commodo</h2>
<p>
    Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>

<h2>consectetuer adipiscing</h2>
<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, 
</p>

这里我想得到最后两个'p'标签(动态)。


这是我的PHP代码:

$dom = new DOMDocument();
$dom->loadHTMLFile($html_file);
libxml_use_internal_errors(true);

$h2_tags = $dom->getElementsByTagName('h2');

foreach($h2_tags as $single_tag) {

     echo $single_tag->textContent;         
     print_r($single_tag);

}   

这只给了我h2的文字内容。但是在h2之后我需要'p'。 这是可能的还是我需要使用其他课程?

2 个答案:

答案 0 :(得分:2)

您可以尝试以下代码:

$dom = new DOMDocument();
$dom->loadHTMLFile($html_file);
libxml_use_internal_errors(true);

$xpath = new DomXPath($dom);
$nodeList = $xpath->evaluate('//p[preceding::h2]/text()');

foreach ($nodeList as $domElement){
   echo $domElement->textContent."<br><br>";
}

参考输出:http://phpfiddle.org/main/code/7i5-3ir

答案 1 :(得分:0)

<?php

$items = array();

$document = new DOMDocument;
@$document->loadHTMLFile('example.html');

foreach ($document->getElementsByTagName('h2') as $node) {
    while ($node = $node->nextSibling) {
        if ($node->nodeType == XML_ELEMENT_NODE) {
            if ($node->nodeName == 'p') {
                $items[] = $node->textContent;
            }

            break;
        }
    }
}

print_r($items);