Is it possible to cache only a specific part of a page in PHP, or the output of a specific section of code in the PHP script? It seems when I try to cache a particular page, it caches the whole page which is not want I want, some of the content in my page should be updated with every page load while others (such as a dropdown list with data from a database) only needs to be updated every hour or so.
If you are talking about caching by the browser (and any proxies it might interact with), then no. Caching only takes place on complete HTTP resources (i.e. on a per URI basis).
Within your own application, you can cache data so you don't need to (for example) hit the database on every request. Memcached is a popular way to do this.
I would probably use Zend Frameworks Zend_Cache
library for this.
You can just use this component without needing to use the entire framework.
Step over to Zend Framework Download Page and grab the latest.
After you have downloaded the core files, you will need to include Zend_Cache in your project. Zend_Cache docs.
Have you decided how you want to cache your data? Are you using a file system? Or are you memcache? Once you know which you are going to use, you need to use a specific Zend_Cache backend.
Backend documentation: Zend_Cache Backends Frontend documentation: Zend_Cache Frontends
So you would do something like this...
<?php
// configure caching backend strategy
$backend = new Zend_Cache_Backend_Memcached(
array(
'servers' => array( array(
'host' => '127.0.0.1',
'port' => '11211'
) ),
'compression' => true
) );
// configure caching frontend strategy
$frontend = new Zend_Cache_Frontend_Output(
array(
'caching' => true,
'cache_id_prefix' => 'myApp',
'write_control' => true,
'automatic_serialization' => true,
'ignore_user_abort' => true
) );
// build a caching object
$cache = Zend_Cache::factory( $frontend, $backend );
This would create a cache which makes use of the Zend_Cache_Frontend_Output
caching mechanisms.
To use Zend_Cache_Frontend_Output
which is want you want, it would be simple. Instead of the core you would use output
. The options which you pass are identical. Then to use it you would:
// if it is a cache miss, output buffering is triggered
if (!($cache->start('mypage'))) {
// output everything as usual
echo 'Hello world! ';
echo 'This is cached ('.time().') ';
$cache->end(); // output buffering ends
}
echo 'This is never cached ('.time().').';
Useful Blog: http://perevodik.net/en/posts/14/
Sorry this question took longer to write than expected and lots of answers have been written I see!
You could roll your own caching with ob_start(), ob_end_flush() and similar functions. Gather the desired output, dump it into some file or database, and read later if conditions are the same. I usually build md5 sum of the state and restore it later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With