欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php中将一段数据存到一个txt文件中并显示其内容

程序员文章站 2023-09-03 22:59:39
这里的数据可以为基本数据类型,数组,对象等; 在存储的时候可以用serialize进行序列化,但取的时候要先用unserialize反序列化。

这里的数据可以为基本数据类型,数组,对象等;

在存储的时候可以用serialize进行序列化,但取的时候要先用unserialize反序列化。

<?php
  $data = array("上海","西安","北京");

  //将数组存到指定的text文件中
  file_put_contents("e:/data.txt",serialize($data));
  //获取数据
  $datas = unserialize(file_get_contents("e:/data.txt"));
  print_r($datas);
?>

当然也可以使用json_encode,这里数组可以以键值对存取,取时要用json_decode转义。

<?php
  $data = array("现代"=>"上海","文化"=>"西安","首都"=>"北京");

  //将数组存到指定的text文件中
  file_put_contents("e:/data.txt",json_encode($data));
  //获取数据
  $datas = json_decode(file_get_contents("e:/data.txt"));
  print_r($datas);
?>