2013-02-14 160 views
0

好吧,标题是模糊的,但我不知道如何说出这个。php在使用SimpleHTMLDOM呈现之前呈现页面的内容

我想要做的是解析渲染之前整个页面内容,然后选择使用Simple HTML DOM PHP的页面一定的股利和渲染,而不是整个页面,如果页面的header通过if(isset($_SERVER[]呼叫匹配

麻烦是,我不知道该怎么做,我不能选择使用PHP的当前页面(使用$_SERVER[]?)。我甚至不知道我是否有道理。

说,我们开始与外部库是如何工作的:

$html = file_get_html(''); // Get HTML of this page.. somehow 
$div = $html->find('div[id=mainContent]'); // or 'div#mainContent' 

但我怎么回显div的内容?并且这会首先渲染页面?

任何人都可以帮助我吗?

回答

1

您可以使用建议的​​,以更清洁的方式获得此选项。通过适当使用核心PHP指令和包含,你可以做到这一点,所以你不必触摸现有的PHP文件在所有

<?php 
    // This goes before the page, and this can be done automatically (i.e. without 
    // modifying the existing PHP file) using auto prepend: 
    // http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file 
    ob_start(); 
?> 

// The "old" page ... 

<?php 
    // This goes after the page, and again can be done automatically using 
    // auto append (see above). 
    // This 'if' can also check whether this page is one of those that must be 
    // manipulated, or not. 
    if(!isset($_SERVER['EXAMPLE_HEADER']) || ('false'==$_SERVER['EXAMPLE_HEADER'])) 
    { 
     $html = ob_get_clean(); 

     // Include is only necessary in this scope -- full path may be needed, though 
     include_once('simple_html_dom.php'); 

     // Here, $html is parsed to yield a DOM object 
     // ... 

     foreach($dom->find('div[id=mainContent]') as $div) 
     { 
      echo $div->innertext; 
     } 
?> 
+0

比我的回答容易得多,效率也更高! – Ricki 2013-02-27 18:18:02

1

尝试使用ob_startob_get_clean :)

ob_start(); 

echo "Hello World"; 

$html = ob_get_clean(); 

现在$html将包含"Hello World"ob_start();需要在您的代码的开头,并且ob_get_clean();您想停止收集内容。

+0

我已经看过'ob_start',但没想到它会工作,任何指向教程的链接? – Ricki 2013-02-14 18:42:21

+0

请参阅ob_get_clean中的示例。这解决了您获取页面的HTML代码的问题。 – MarcinWolny 2013-02-14 18:44:22

+0

我看,从看手册,我不认为这是相当我即时寻找,因为我可以得到的HTML。但使用'ob_start'可能会朝着正确的方向 – Ricki 2013-02-14 18:47:02

0

我工作了下面有一个示例页面:

<?php 
include_once('simple_html_dom.php'); 

if(!isset($_SERVER['EXAMPLE_HEADER']) && $_SERVER['EXAMPLE_HEADER'] == 'false'){ ?> 

<html> 
<head></head> 
<body></body> 
</html> 

<?php 
}else{ 
$html = file_get_html('thispage.html'); 
foreach($html->find('div[id=mainContent]') as $div) { 
echo $div->innertext; 
} ?> 

显然HTML代码示例应该是你的页面。因此,页面会询问是否发送了页眉,如果不是,则会像往常一样显示页面,如果是,则会搜索页面中特定的div(在此例中为mainContent),然后显示该页面。

这将帮助其他人我猜。但使用ob_start也可以提供帮助!