note 42483 added to function.var-export
| From: | Haravikk at rn2 dot php dot net | Date: | Tue, 18 May 2004 16:37:42 +0000 |
| Subject: | note 42483 added to function.var-export | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-69779@lists.php.net to get a copy of this message | ||
I created this little function to output a variable of any kind (including arrays) in such a format
that they can be saved and later included by PHP to immediately gain access to the now cached
variable. It supports nested arrays through the recursive nature of it.
Note that $phpEx is the extension being used by PHP, and $rootdir is a path to the root directory
from which the script is operating, they aren't really necessary but many sites could require
them.
<?php
function cache_variable ($variable, $name) {
global $phpEx, $rootdir;
// A variable called $name has been passed to us for caching as a file of the same name, create
// the file header
$file = "<?php\n";
$file .= "if (!defined('SECURE')) die ('Hacking attempt');\n";
$content = cache_variable_recur ($variable);
$file .= "$$name = $content;\n";
// Finish the file
$file .= '?>';
$handle = fopen ($rootdir . 'cache/' . $name.$phpEx, 'w');
fwrite ($handle, $file);
fclose ($handle);
}
function cache_variable_recur ($input) {
if (is_array ($input)) {
$content .= 'array (';
foreach ($input as $k => $v) {
$parts[] = "'$k' => " . cache_variable_recur ($v);
}
$content .= implode (', ', $parts).')';
} else {
$input = addcslashes ($input, "'");
$content .= "'$input'";
}
return $content;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.var-export.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42483
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42483&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42483&report=yes
Search -- http://master.php.net/manage/user-notes.php