Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 文件编程(二)-读取文件的四种方式

PHP 文件编程(二)-读取文件的四种方式

WBOY
WBOYOriginal
2016-07-25 08:59:261028Durchsuche
  1. //读取文件

  2. $file_path="text.txt";
  3. if(!file_exists($file_path)){

  4. echo "文件不存在";
  5. exit();
  6. }
  7. //打开文件
  8. $fp=fopen($file_path,"a+");
  9. //读取文件
  10. $content=fread($fp,filesize($file_path));
  11. echo "文件内容是:
    ";
  12. //默认情况下把内容输出到网页后,不会换行显示,因为网页不识别\r\n
  13. //所有要把\r\n =>
  14. $content=str_replace("\r\n","
    ",$content);
  15. echo $content;
  16. fclose($fp);

  17. ?>
复制代码

2、读取文件的第二种方式

  1. //第二种读取文件的方式

  2. $file_path="text.txt";

  3. if(!file_exists($file_path)){
  4. echo "文件不存在";
  5. exit();
  6. }
  7. $content=file_get_contents($file_path);
  8. $content=str_replace("\r\n","
    ",$content);

  9. echo $content;
  10. ?>
复制代码

3、循环读取(对付大文件)的方式

  1. //第三种读取方法,循环读取(对付大文件)

  2. $file_path="text.txt";

  3. if(!file_exists($file_path)){
  4. echo "文件不存在";
  5. exit();
  6. }
  7. //打开文件

  8. $fp=fopen($file_path,"a+");
  9. //定义每次读取的多少字节
  10. $buffer=1024;
  11. //一边读取。一边判断是否达到文件末尾
  12. while(!feof($fp)){
  13. //按1024个字节读取数据
  14. $content=fread($fp,$buffer);
  15. echo $content;
  16. }
  17. fclose($fp);

  18. ?>
复制代码

4、读取ini配置文件 1)、db.ini 文件

  1. $arr=parse_ini_file("db.ini");

  2. echo "
    ";
  3. print_r($arr);
  4. echo "";
  5. echo $arr['host'];
  6. //连接数据库

  7. $conn = mysql_connect($arr['host'], $arr['user'], $arr['pwd']);
  8. if(!$conn){

  9. echo "error";
  10. }
  11. echo "OK";

  12. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn