php读取文件的方法
1.读取文件到数组
$file=file('filename') 此函数可以把文件内容 当做数组读入 $lines=count($file) 用于读取行数
可以通过以下循环来输出文件内容,for($i=0;$i<$count;$i++){echo "htmlspecialchars($file[$i])"}
2.读取文件到字符串
$file=file_get_contents("filename") 此函数把文件内容读入字符串$file 中,strip_tags($file) 用于删除标记例如
... 输出文件内容用 echo htmlspecialchars($file) 即可
3.读取文件内容到屏幕
readfile("filename");
以上函数都不用文件句柄
1.fread函数的使用
fopen 可以打开一个文件 返回句柄 fclose关闭
当处理较小的文件时候,可以用fread(句柄,字节数) $conyent=fread($file,filesize(filename))
2.fgets函数的使用
当打开一个大文件时,为了避免文件内容占用内存,用fgets实现,fgets函数取得从当前位置到下一个换行符之间的文件块
$content=fgets(句柄)
其他的文件读取函数
fgetss它除了能像strip_tags去除HTML标记外,其余的与fgets一样
fgetcsv处理csv文件变得简单
像文件中写入
fwrite(句柄,内容)
file_exists($filename) 检查文件是否存在
is_file($filename) 检查是否是文件
is_readable($filename)检查是否可读
is_writeable($filename)检查是否可写
有关目录的函数
1.使用opendir,readdir,colsedir函数
<?php
$location="./";
$dp=opendir($location);
while($entry=readdir($dp)){
if(is_dir($entry)){
echo $location.$entry."是个目录
";
}elseif(is_file($entry)){
echo $location.$entry."是个文件
";
}
}
closedir($dp);
?>
2.使用dir伪类
例子
<?php
$location='../';
$dir=dir($location);
while($entry=$dir->read()){
if(is_dir($entry)){
echo $location.$entry."是个目录
";
}elseif(is_file($entry)){
echo $location.$entry."是个文件
";
}
}
$dir->close();
?>
显示php源代码
highlight_string($yuanma)显示源代码
highlight_file($filename)显示文件的源代码
<?php
$d="<?php echo 'hi';?>";
highlight_string($d);
echo "
";
highlight_file("sort.php");
?>
读取ini文件函数
ini文件如下
;seeting to connect to mysql
[database_setting]
host=localhost
user=root
pass=
dbname=produce
php代码如下
<?php
$ini=parse_ini_file("example.ini",TRUE);
print_r($ini);
?>
使用php中的标准php库操作文件
directoryiterator类是spl中的一部分 该类是一种读取文件目录和获取文件信息的方法非常方便的方法
例子
try{
foreach (directoryiteator(目录名) as $item){
echo "文件名".$item->getFilename()"
";
}
echo "类中的方法
";
foreach(get_class_methods('directoryiterator') as $method){
echo $method."
";
}
}
catch(Exception as $r){
echo "错误是".$e->getMessage()."\n";
}
?>