php 使用fopen函数创建、打开文件详解及实例代码

2019-05-03 00:34:04王旭

2、使用fopen函数打开文件:

$my_file = 'file.txt';//假设文件file.txt存在
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //open file for writing ('w','r','a')...


3、fopen函数结合fread读取文件:

$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));


4、fopen函数结合fwrite函数写文件

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);

5、fopen函数结合fwrite函数向文件中追加内容:

$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "n".'New data line 2';
fwrite($handle, $new_data);

6、fopen() 函数还可用于打开互联网上的 URL 地址:

<?php
$fh = fopen("http://www.baidu.com/", "r");
if($fh){
  while(!feof($fh)) {
    echo fgets($fh);
  }
}
?>

注意:fopen() 返回的只是一个资源,要想显示打开的页面地址,还需要用 fgets() 函数读取并输出。

通过此文希望能帮助到大家,谢谢大家对本站的支持!

相关文章 大家在看