<?php// http://www.jb51.net/article/23093.htmfunction set_cache($name, $value) { // 設定相對或者絕對目錄,末尾不要加 "/" $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的字串,傳josn字串,快取頁面變數存的就是josn字串,傳數組,快取頁面變數存的就是數組,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/>";// 緩衝另一種方法,用serialize把數組序號成字串,存放在任意副檔名檔案中,使用時用fopen開啟讀取其中字串內容,再用unserialize還原序列化成原資料$serialize_str = serialize ( $test_array );echo $serialize_str; // 這個就是描述過的數組但在這裡是一個字串而已echo "<br/>";$unserialize_str = unserialize ( $serialize_str ); // 把描述過的資料恢複var_dump($unserialize_str); //還原成為 $test_array ,數組結構並沒有丟失。?>