简体   繁体   English

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

[英]HTML DOMDocument get string from tags following paragraph

I want to parse html documents. 我想解析HTML文档。 I need the the contents of all 'p' after 'h2'. 我需要'h2'之后所有'p'的内容。

The html to parse: (example) 要解析的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>

Here I want to get the last two 'p' tags (dynamically). 在这里,我想获得最后两个'p'标签(动态)。


Here my PHP Code: 这是我的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);

}   

This only gives me the text content of the h2. 这只给了我h2的文本内容。 But I need the 'p' after the h2. 但是在h2之后我需要'p'。 Is this possible or do I need to use an other class? 这是可能的还是我需要使用其他课程?

You can try the following code: 您可以尝试以下代码:

$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>";
}

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

<?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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM