2015-10-01 54 views
3

我需要使用TCPDF和PHP制作PDF生成器。我可以将所有内容写在PDF上,但这看起来很糟糕。因此,我需要将HTML中的每个产品都放在不同的页面上。获取2个元素之间的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>" 

我有必要时包括一些到服务器上的文件没有问题,但最好不。

+0

如果你知道所有的可能性,这些网页可能看起来,你可以使用正则表达式来提取正是你在所有的情况下需要这个工作的数据... –

回答

5

如果页面看起来像您的示例,您可以尝试一个简单的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>" 
} 
+0

对于我来说,谢谢 – FlorisdG

+0

不用客气,我只是编辑了答案,并添加了一个链接,您可以在这里测试,如果有些页面与您的示例不同 – swidmann