如何打破ob_start()并在一些标签后继续

问题描述:

我想构建电子商务平台的缓存系统。如何打破ob_start()并在一些标签后继续

我选择在页面末尾使用ob_start('callback')ob_end_flush()

我将验证是否有为访问的url创建的任何.cache文件,并且如果有文件,我将打印其内容。

我的问题是,我想保持购物车的生活,所以我不想缓存它。我怎样才能做到这一点?

<?php 

    function my_cache_function($content) { 
     return $content; 
    } 

    ob_start('my_cache_function'); 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>test</title> 
</head> 
<body> 
    test 
    <?php 
     //some ob_break() ? 
    ?> 
    <div id="shopping-cart"> 
     this should be the content I do not want to cache it 
    </div> 
    <?php 
     // ob_continue() ? 
    ?> 

</body> 
</html> 
<?php 
    ob_end_flush(); 
?> 

预先感谢您!

如果你这样做,问题是内容将输出之前的任何HTML放在之前。您可能需要的是将该内容保存在某个变量中,然后在缓存“模板”文件中使用占位符,例如%SHOPPING-CART%

因此,您可以用str_replace替换为真实的非缓存内容。

+0

即使用户未登录,购物车仍然可用。当用户登录时,将不存在缓存,因此我不想缓存的唯一项目是购物车,它将在每个页面上可见。我相信你的解决方案能够工作,所以谢谢你的回答。我不明白为什么我直到现在才意识到:)) –

你可以这样说:

<?php 

    function my_cache_function($content) { 
     return $content; 
    } 
    $output = ""; 
    ob_start('my_cache_function'); 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>test</title> 
</head> 
<body> 
    test 
    <?php 
     $output .= ob_get_clean(); 
    ?> 
    <div id="shopping-cart"> 
     this should be the content I do not want to cache it 
    </div> 
    <?php 
     ob_start(); 
    ?> 

</body> 
</html> 
<?php 
     $output .= ob_get_clean(); 
     echo $output; 
?> 

即使并没有真正意义。

我不确定Zulakis解决方案会一路走下去......这个改动怎么样?

<?php 
$pleaseCache=true; 
function my_cache_function($content) { 
    if($pleaseCache) 
    { 
     /// do your caching 
    } 
    return $content; 
} 
$output = ""; 
ob_start('my_cache_function'); 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>test</title> 
</head> 
<body> 
    test 
    <?php 
     $output .= ob_get_clean(); 
     $pleaseCache = false; 
     ob_start('my_cache_function'); 
    ?> 
    <div id="shopping-cart"> 
     this should be the content I do not want to cache it 
    </div> 
    <?php 
     $output .= ob_get_clean(); 
     $pleaseCache = true; 
     ob_start('my_cache_function'); 
    ?> 

</body> 
</html> 
<?php 
    $output .= ob_get_clean(); 
    ob_end_clean(); 
    echo $output; 
?> 

同样,不知道这使得有很大的意义......但你有你的原因,我预设。

+0

谢谢你的回答..我给你和@Zulakis +1,因为你已经尝试了我所要求的。不幸的是,有人误解了,我认为blue112解决方案是最好的。即使我使用您的解决方案,购物车也将无法正常运行如果我已从缓存文件中获取该文件, –