深入PHP数据缓存的使用说明


<?php
// https://www.jb51.net/article/23093.htm
function set_cache($name, $value) {
    // 设置相对或者绝对目录,末尾不要加 "https://www.jb51.net/"
    $cache_dir = "./cache";
    // 设置扩展名
    $cache_extension = ".php";

    $cache_str_begin = "<?php\n//Cache Created at: " . date ( "Y-m-d H:i:s" ) . "\n";
    if (! is_array ( $value )) {
        $cache_str_middle = "\$$name = \"$value\";";
    } else {
        $cache_str_middle = "\$$name = " . arrayeval ( $value ) . ";";
    }
    $cache_str_end = "\n?>";

    $cache_str = $cache_str_begin . $cache_str_middle . $cache_str_end;

    // 缓存文件路径
    $cache_file = "$cache_dir/$name$cache_extension";
    if ($fp = @fopen ( $cache_file, "wb" )) {
        fwrite ( $fp, $cache_str );
        fclose ( $fp );
        return true;
    } else {
        echo $cache_file;
        exit ( "Can not write to cache files, please check cache directory " );
        return false;
    }
}

// 将array变成字符串, 来自discuz!
function arrayeval($array, $level = 0) {
    if (! is_array ( $array )) {
        return "\"$array\"";
    }

    $space = "";
    for($i = 0; $i <= $level; $i ++) {
        $space .= "\t";
    }
    $evaluate = "Array\n$space(\n";
    $comma = $space;
    if (is_array ( $array )) {
        foreach ( $array as $key => $val ) {
            $key = is_string ( $key ) ? "\"" . addcslashes ( $key, "\"\\" ) . "\"" : $key;
            $val = ! is_array ( $val ) && (! preg_match ( "/^\-?[1-9]\d*$/", $val ) || strlen ( $val ) > 12) ? "\"" . addcslashes ( $val, "\"\\" ) . "\"" : $val;
            if (is_array ( $val )) {
                $evaluate .= "$comma$key => " . arrayeval ( $val, $level + 1 );
            } else {
                $evaluate .= "$comma$key => $val";
            }
            $comma = ",\n$space";
        }
    }
    $evaluate .= "\n$space)";
    return $evaluate;
}

$test_array = array (
        "6b" => "a\\",
        "b",
        "c",
        array (
                "c",
                "d"
        )
);

$fileAndVarName = "newFile";

// 在生成$encode_str的时候,为使字符串中原有字符格式不变,系统在编译时会给字符串中预定义字符前加 \ 使预定义字符保留在字符串中,但输出或打印字符串的时候只会输出打印出预定义字符,不会打印出预定义字符前面的 \
$encode_str = json_encode ( $test_array );
// 因为这里要把字符串打印成PHP代码,输出的时候,字符串中预定义字符会打乱程序运行,所以要在原有转义字符前再加转移字符,使字符串输出打印时在预定义字符前转义字符也能输出
$addslashes_str = addslashes ( $encode_str ); // addslashes将字符串中预定义字符前加 \ 使其能存放在字符串中不产生作用,不参与程序运行
echo stripslashes($addslashes_str); // 反转义函数,可去掉字符串中的反斜线字符。若是连续二个反斜线,则去掉一个,留下一个。若只有一个反斜线,就直接去掉。
echo "<br>";


// 可以传数组对象,也可以传转换成json的字符串,转换成json字符串,使用时需要再转换成数组
set_cache ( "$fileAndVarName", $addslashes_str );
var_dump ( $addslashes_str );
echo "<br/>";
include_once "./cache/$fileAndVarName.php";
var_dump ( $$fileAndVarName );
echo "<br/>";

$decode_arr = ( array ) json_decode ( $$fileAndVarName );
var_dump ( $decode_arr );
echo "<br/>";

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/df7e26383b3787e3b5508cc70354164d.html