<?php
echo '<h2>文件操作</h2><hr color="green">';
/**
* 步骤:
* 1.打开文件
* 2.操作文件
* 3.关闭文件
*
*/
//1.创建或打开一个本地文件
//以只读(r)方式打开一个本地文件,不会创建新文件. r+(读写)
//打开成功会返回一个文件资源:句柄
// $fh = fopen('file1.txt','r') or die('不能打开file1.txt');
// //以只写(w)方式打开文件,如果文件不存在则自动创建一个,w+读写
// $fh = fopen('file2.txt','w') or die('不能打开file2.txt');
// //以追加的方式(a只写》如果文件不存在则自动创建一个,a+读写,指针在末尾
// $fh = fopen('file3.txt','a') or die('不能打开file3.exe');
// //windows系统建议在稳健的操作模式后面添加一个b,(二进制),rb,wb,ab
// //2.打开一个进程的文件
// $fh = fopen('http://www.php.cn/course/801.html','r') or die('打开失败');
//3.读取文件
//fgets($fh)
//fgetss($fh),过滤掉字符串中的html标签
// while($s=fgets($fh)) {
// print $s;
// }
// while($s=fgetss($fh)) {
// print $s;
// }
// file_get_contents('file.txt');
// echo $content,'<br>';
//4.读取文件到字符串
// $content = file_get_contents('file.txt');
// if (strlen($content)>0) {
// echo $content, '<br>';
// }
// echo strlen($content),'<br>';
// echo mb_strlen($content),'<br>';
//5.读取文件到数组中:file()
$arr = file('maxim.txt');
// echo '<pre>';
// print_r($arr);
// echo '<hr color="green">';
// foreach ($arr as $key => $value) {
// echo $key.':'.$value.'<hr>';
// }
// array_rand($arr ,$length=1); //从数组中随机取出一个或多个
// echo $arr[array_rand($arr)]; //随机返回键值
$length = $_GET['n'];
$keys = array_rand($arr, $length);
print_r($keys);
echo '<hr>';
foreach ($keys as $value) {
print $arr[$value].'<hr>';
}
//文件关闭
// fclose($fh);点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号