Home > Backend Development > PHP Tutorial > How to write array to file in php_PHP tutorial

How to write array to file in php_PHP tutorial

WBOY
Release: 2016-07-13 17:10:37
Original
846 people have browsed it

In PHP, we are provided with a function var_export, which can directly import PHP code into a file.

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

var_export($times,true);后面不加true不能写入文件哟
$fp = fopen('aa.txt','w+');
fwrite($fp,var_export($times,true));
fclose($fp);

Copy code

var_export($times,true); the file cannot be written without adding true at the end
$fp = fopen('aa.txt','w+');
fwrite($fp,var_export($times,true));
fclose($fp);

 代码如下 复制代码

if(isset($_POST['sub'])){    
 $cfg = array('contact'=>$_POST['contact']); //把数据存入数组   
 file_put_contents('./data/contact.cache',serialize($cfg));
        //把数组序列化之后,写到contact.cache里,
 $this->redirect('other/contact');//跳转
 }
 else{    
 $fp = fopen('./data/contact.cache','r');//读
 $cf = unserialize(fread($fp,filesize('./data/contact.cache')));//反序列化,并赋值
 $this->assign('cfg',$cf);//送到前台模板
 $this->display('other/contact');
 }

Method 2

Use serializ and unserialize functions

The code is as follows Copy code
if(isset($_POST['sub'])){ 
$cfg = array('contact'=>$_POST['contact']); //Save data into array
file_put_contents('./data/contact.cache',serialize($cfg));
//After serializing the array, write it into contact.cache,
$this->redirect('other/contact');//Jump
}
else{ 
$fp = fopen('./data/contact.cache','r');//read
$cf = unserialize(fread($fp,filesize('./data/contact.cache')));//Deserialize and assign value
$this->assign('cfg',$cf);//Send to the front desk template
$this->display('other/contact');
} http://www.bkjia.com/PHPjc/629652.html
www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629652.htmlTechArticle provides us with a function var_export in php, which can directly put the php code into a file. The code is as follows. Copy the code var_export($times,true); it cannot be written without adding true after it...
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