gpt4 book ai didi

php - 获取 2 个元素之间的 HTML 内容

转载 作者:可可西里 更新时间:2023-11-01 00:42:06 25 4
gpt4 key购买 nike

我需要使用 TCPDF 和 PHP 制作一个 PDF 生成器。我可以将所有内容都写在 PDF 上,但这看起来很糟糕。因此,我需要在不同的页面上获取 HTML 中的每个产品。

使用较新的页面,这很容易。只需使用 dom 文档即可找到 <div>围绕产品,将其放入数组中并将其写入 PDF。

不幸的是,不是每个页面都一样,所以不是每个页面都有<div> .例如这个页面。

'<h3>sample#1</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<img>
<table>
</table>

<h3>sample#2</h3>
<p>Aenean commodo ligula eget dolor. Aenean massa.</p>
<img>
<table>
</table>

<h3>sample#3</h3>
<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
<img>
<table>
</table>

<h3>sample#4</h3>
<p>Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>
<img>
<table>
</table>'

所以我想得到的是这样的:

array (size=4)
0 => string "
<h3>sample#1</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<img>
<table>
</table>"
1=> string "
<h3>sample#2</h3>
<p>Aenean commodo ligula eget dolor. Aenean massa.</p>
<img>
<table>
</table>"

等等

如果需要,我可以在服务器文件中包含一些内容,但最好不要。

最佳答案

如果页面确实像您给出的示例,您可以尝试使用简单的 preg_match_all() .如果某些页面的结构与您的示例不同,您可以调整正则表达式。 Here是测试功能的好网站。

$html = '<h3>sample#1</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<img>
<table>
</table>

<h3>sample#2</h3>
<p>Aenean commodo ligula eget dolor. Aenean massa.</p>
<img>
<table>
</table>

<h3>sample#3</h3>
<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
<img>
<table>
</table>

<h3>sample#4</h3>
<p>Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>
<img>
<table>
</table>';


$matches = array();
$elements = array();

preg_match_all( "#<h3>.*?</table>#s" , $html, $matches );

if( count( $matches[0] ) > 1 ) {
$elements = $matches[0];
}

echo "<pre>";
var_dump( $elements );

输出:

array(4) {
[0]=>
string(105) "<h3>sample#1</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<img>
<table>
</table>"
[1]=>
string(95) "<h3>sample#2</h3>
<p>Aenean commodo ligula eget dolor. Aenean massa.</p>
<img>
<table>
</table>"
[2]=>
string(133) "<h3>sample#3</h3>
<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
<img>
<table>
</table>"
[3]=>
string(116) "<h3>sample#4</h3>
<p>Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>
<img>
<table>
</table>"
}

关于php - 获取 2 个元素之间的 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com