php读取文件的几个常用函数
php读取文件的几个常用函数:
1、file_get_contents:file_get_contents() 函数把整个文件读入一个字符串中,和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串.
file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法,如果操作系统支持,还会使用内存映射技术来增强性能.
语法:file_get_contents(path,include_path,context,start,max_length
<?php $url = "http://www.phprm.com"; $contents = file_get_contents($url); //如果出现中文乱码请加入以下代码 //$getcontent=iconv("gb2312","utf-8",file_get_contents($url)); //echo $getcontent; echo $contents; ?>
2、curl:如果您看到的话,那么您需要设置您的php并开启这个库,如果您是在windows平台下,那么非常简单,您需要改一改您的php.ini文件的设置,找到php_curl.dll,并取消前面的分号注释就行了,如下所示:
//取消下在的注释,extension=php_curl.dll,实例代码如下:
<?php $url = "http://www.phprm.com"; $ch = curl_init(); $timeout = 5; curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_connecttimeout, $timeout); //在需要用户检测的网页里增加下面两行 //curl_setopt($ch,curlopt_httpauth,curlauth_any); //curl_setopt($ch,curlopt_userpwd,us_name.":".us_pwd); $contents = curl_exec($ch); curl_close($ch); echo $contents; ?>
3、fopen->fread->fclose,fopen函数详细说明.
定义和用法:fopen() 函数打开文件或者 url,如果打开失败,本函数返回 false.
语法:fopen(filename,mode,include_path,context)
参数 描述
filename 必需,规定要打开的文件或 url.
mode 必需,规定要求到该文件/流的访问类型.
include_path 可选,如果也需要在 include_path 中检索文件的话,可以将该参数设为 1 或 true.
context 可选。规
"r" 只读方式打开,将文件指针指向文件头.
"r+" 读写方式打开,将文件指针指向文件头.
"w" 写入方式打开,将文件指针指向文件头并将文件大小截为零,创建.
"w+" 读写方式打开,将文件指针指向文件头并将文件大小截为零,创建.
"a" 写入方式打开,将文件指针指向文件末尾,文件不存在创建.
"a+" 读写方式打开,将文件指针指向文件末尾,文件不存在创建.
PHP实例代码如下:
<?php $handle = fopen("http://www.phprm.com", "rb"); $contents = ""; do { $data = fread($handle, 8192); if (strlen($data) == 0) { break; } $contents.= $data; } while (true); fclose($handle); echo $contents; ?>
本文地址:http://www.phprm.com/wenjian/fs4193.html
转载随意,但请附上文章地址:-)