我需要使用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 );
OUTPUT:
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>"
}