把php代码保存到php文件实现方法
很多时间我们需要把php生成的php代码保存到php文件里面,像如果利用到缓存时一些基础数据就直接保存到了一个指定的php缓存文件了,下面我们来看看实例。
<?php function cacheArr(&$data) { if (!$data) throw new Exception('数组不能为空'); foreach ($GLOBALS as $key => $value) { $str = $GLOBALS[$key]; $GLOBALS[$key] = 'changed'; if (&$data == 'changed') { $strName = $key; break; } $GLOBALS[$key] = $str; } ob_clean(); ob_start(); echo "<?php\n"; function echoArr($arr, $arrName) { $arrCount = count($arr); $i == 0; foreach ($arr as $key => $value) { ++$i; if (is_array($value)) { echo "\n" . (is_numeric($key) ? $key : '\'' . $key . '\'') . '=>array('; echoArr($value, $arrName . (is_numeric($key) ? '[' . $key . ']' : '[\'' . $key . '\']')); if ($i != $arrCount) echo '),'; else echo ')'; continue; } if ($i != $arrCount) echo ((is_numeric($key)) ? $key : '\'' . $key . '\'') . '=>' . (is_numeric($value) ? $value: '\'' . $value . '\'') . ','; else echo ((is_numeric($key)) ? $key : '\'' . $key . '\'') . '=>' . (is_numeric($value) ? $value : '\'' . $value . '\''); } } echo '$' . $strName . '=array('; echoArr($data, ''); echo ');'; echo "\n"; $file = fopen($strName . '.arr.php', 'w'); fwrite($file, ob_get_contents()); fclose($file); ob_clean(); return true; } ?>
实例代码如下:
<?php //存储数组 $hello = array( 1 => 'test', 2 => array( 'hello123' ) ); cacheArr($hello); unset($hello); //读取数组 require 'hello.arr.php'; print_r($hello); ?>
教程链接:http://www.phprm.com/develop/fs1022.html
随意转载~但请保留教程地址★