提问人:ISFT 提问时间:3/21/2023 最后编辑:ISFT 更新时间:7/28/2023 访问量:139
简单的 HTML DOM 解析器:获取元素之间的 HTML
simple html dom parser get html between elements
问:
我正在使用 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>
答:
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>
评论
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;
上一个:如何从不同的目录路径和深度中包含
评论
First text
div p