I’m struggling to create web page caches with the Transient API. When I try to save the whole source code, something goes wrong. I’m suspecting that WordPress internally correct the format. In that case, is there a good way to save data intact?
The below code is ready to run as a plugin and demonstrates the problem. When the cache is not created, it shows a web page but once it is created and tries to show the cached data, a blank page is displayed.
<?php
/* Plugin Name: Sample Transient */
add_action('admin_menu', 'sample_transient_menu');
function sample_transient_menu() {
add_options_page(
'Sample Transient',
'Sample Transient',
'manage_options',
'sample_transient',
'sample_transient_admin');
}
function sample_transient_admin() {
?>
<div class="wrap">
<?php
$strTransient = 'sample_transient_html';
$html = get_transient($strTransient);
if( false === $html ) {
echo 'cache is not used: ' . $strTransient . '<br />';
$html = wp_remote_get('http://www.google.com');
$html = $html['body'];
// $html = '<div>hello world</div>'; // <-- this works fine
set_transient($strTransient, htmlspecialchars($html), 60 );
$tmp = get_transient($strTransient);
if (false === $tmp)
echo 'transient is not saved.';
else
echo 'transient is now saved: ' . $strTransient;
} else
echo 'cache is used. <br />';
print_r(htmlspecialchars_decode($html));
?>
</div>
<?php
}
[Edit]
Also, it would be appreciated if somebody can provide a solution for the encoding problem. Currently it just shows broken characters.
Encrypting the strings just worked. I’m not sure about the speed though.
Reference: Best way to use PHP to encrypt and decrypt passwords?