简单的 HTML DOM 解析器:获取元素之间的 HTML

simple html dom parser get html between elements

提问人:ISFT 提问时间:3/21/2023 最后编辑:ISFT 更新时间:7/28/2023 访问量:139

问:

我正在使用 PHP 简单 HTML Dom 库从网页获取 HTML。我需要在“div.page-content”内的第一个标签和第一个“h4”标签之间获取 HTML。例:

<div class="page-content">
   First text
   <p>Second text</p>
   <div>Third text</div>
   <p>More text</p>
   <h4>Subtitle 1</h4>
   <p>bla bla</p>
   <p>bla bla</p>
   <h4>Subtitle 2</h4>
   <p>bla bla</p>
   <p>bla bla</p>
</div>

我试过这样做:

$start = $html->find('div.page-content', 0);
while ( $next = $start->next_sibling() ) {
    if ( $next->tag == 'h4')
        break;
    else{
        echo $next->plaintext;
        echo '<br/>';
        
        $start = $next;
    }
}

但它不会一无所获。

我需要获取所有:

 First text
 <p>Second text</p>
 <div>Third text</div>
 <p>More text</p>
php html dom

评论

0赞 j08691 3/21/2023
你试过什么?
1赞 Mike 'Pomax' Kamermans 3/21/2023
如果你需要这个字符串,你为什么要从?这将显式跳过第一段标记之前的任何文本。First textdiv p
0赞 ISFT 3/21/2023
@Mike'Pomax'Kamermans对不起,复制/粘贴这个问题是错误的。我已经更新了帖子。
0赞 Mike 'Pomax' Kamermans 3/22/2023
@ISFT为什么呢?有人已经写了一个有效的答案,甚至不需要第三方库。这对你不起作用吗?(如果是这样,请让他们知道原因)

答:

0赞 Chris Haas 3/21/2023 #1

我以前从未使用过 PHP Simple HTML Dom 库,但使用本机可以很容易地做到这一点:DOMDocument

$html = <<<EOT
<body>
<div class="page-content">
   First text
   <p>Second text</p>
   <div>Third text</div>
   <p>More text</p>
   <h4>Subtitle 1</h4>
   <p>bla bla</p>
   <p>bla bla</p>
   <h4>Subtitle 2</h4>
   <p>bla bla</p>
   <p>bla bla</p>
</div>
</body>
EOT;

$doc = new DOMDocument();
$doc->loadHTML($html);

// Get our node by class name
// See https://stackoverflow.com/a/6366390/231316
$finder = new DomXPath($doc);
$classname = "page-content";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

$buf = '';
foreach ($nodes as $node) {
    foreach ($node->childNodes as $child) {
        if ($child->nodeName === 'h4') {
            break;
        }
        $buf .= $doc->saveHTML($child);
    }
}

echo $buf;

输出以下内容,其中包括空格:

   First text
   <p>Second text</p>
   <div>Third text</div>
   <p>More text</p>
   

演示:https://3v4l.org/JWUi5

评论

0赞 ISFT 3/21/2023
非常感谢,但我必须使用“简单的html dom”php库来做
0赞 Radical_Activity 7/28/2023 #2

您可以通过遍历 div.page-content 的所有子元素来修改您的方法,并在遇到第一个 h4 标签时停止。下面是一个修改后的代码片段,应该适用于你的情况:

// Assuming you have already loaded the HTML into $html using the library.

// Find the first div.page-content
$pageContent = $html->find('div.page-content', 0);

// Initialize an empty string to store the extracted HTML
$extractedHtml = '';

// Iterate through all child elements of div.page-content
foreach ($pageContent->children() as $child) {
    // Check if the current child is an h4 tag
    if ($child->tag == 'h4') {
        break; // Stop when we encounter the first h4 tag
    } else {
        // Append the HTML of the current child to the extractedHtml
        $extractedHtml .= $child->outertext;
    }
}

// Output the extracted HTML
echo $extractedHtml;