Home > Backend Development > PHP Tutorial > How to save php code to php file_PHP tutorial

How to save php code to php file_PHP tutorial

WBOY
Release: 2016-07-13 16:55:35
Original
920 people have browsed it

Many times we need to save the PHP code generated by PHP into the PHP file. For example, if the cache is used, some basic data will be directly saved to a specified PHP cache file. Let's take a look at an example.

 代码如下 复制代码
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 " 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;
}
?>

Example

The code is as follows
 代码如下 复制代码


//存储数组
$hello=array(1=>'test',2=>array('hello123'));
cacheArr($hello);
unset($hello);
//读取数组
require 'hello.arr.php';
print_r($hello);
?>

Copy code

//Storage array
$hello=array(1=>'test',2=>array('hello123'));
cacheArr($hello);
unset($hello);
//Read array
require 'hello.arr.php';
print_r($hello);
?>

http://www.bkjia.com/PHPjc/631651.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/631651.html
TechArticle
Many times we need to save the php code generated by php into the php file, such as some basics if caching is used The data is saved directly to a specified php cache file, below...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template