PHP文件操作方法汇总_php技巧

WBOY
Release: 2016-05-16 20:12:26
Original
1231 people have browsed it

在data文件中写入数据:

 <&#63;php
 /**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/29
 * Time: 17:05
 */
 header("Content-type: text/html; charset=utf-8");
 //write data
 $f = fopen('data','w');//打开文件
 fwrite($f,'Hello PHP');//写入数据
 fclose($f);//关闭文件
 echo 'OK';
 //windows环境暂时不考虑权限问题

Copy after login

写入成功后可以在页面看到“OK”

接下来读取data文件里的数据

<&#63;php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/29
 * Time: 17:05
 */
header("Content-type: text/html; charset=utf-8");

//read data
$f = fopen('data','r');
$content = fgets($f);
echo $content;
fclose($f);

Copy after login

如果有多行数据该怎么读取?

方法一 while:

<&#63;php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/29
 * Time: 17:05
 */
header("Content-type: text/html; charset=utf-8");
$f = fopen('data','r');
//读取多行数据 while
while(!feof($f)){//feof() 函数检测是否已到达文件末尾
  $content = fgets($f);
  echo $content;
}
fclose($f);

Copy after login

方法二 file_get_contents():

echo file_get_contents('data');
Copy after login

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
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