file_get_contents函数
一般的也就是使用file_get_contents($url),但是关于这个函数还有很多没有注意到的地方。
先看关于手册:
file_get_contents(path,include_path,context,start,max_length)
参数
描述
path
必需。规定要读取的文件。
include_path
可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 “1″。
context
可选。规定文件句柄的环境。
context 是一套可以修改流的行为的选项。若使用 null,则忽略。
start
可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。
max_length
可选。规定读取的字节数。该参数是 PHP 5.1 新加的。
——————-可以选择读取文件位置和长度这个选项不错。但是关于context的选项是做什么用的呢?
强大的context——stream_context_create
context 就是文本流的意思。而在php中创建文本流的函数是:stream_context_create
参看官方手册:http://php.net/manual/en/function.stream-context-create.php
stream_context_create是用来创建打开文件的上下文件选项的,比如用POST访问,使用代理,发送header等。看到没有之前用curl实现的所谓代理,post,header方法都可以使用file_get_contents+stream_context_create来实现。
之前在《PHP批量采集下载美女图片》中抱怨file_get_contents采集图片时候经常会遇到慢资源造成cpu负载过高,不能设置超时时间,最后使用curl来实现,其实file_get_contents也可以设置超时时间。
file_get_contents超时设置
这样就可以实现设置10s的超时时间
更强大的file_get_contents
file_get_contents实现post
参看官方手册的例子
还可以实现get请求,header代理等等功能,理论上curl可以实现的功能file_get_contents都可以实现,但是关于stream_context_create的解释网络上资源不是很多,也注定在采集程序方面curl的应用更广,另外curl是一种通信模式,不是单纯的php-curl。
之前写过关于解决gzip乱码的问题《:file_get_contents获取gzip网页乱码》
更多高级使用方法参看官方手册的实例:http://php.net/manual/en/function.stream-context-create.php,http://php.net/manual/en/function.file-get-contents.php
file_put_contents函数
语法:
file_put_contents(file,data,mode,context)
参数
描述
file
必需。规定要写入数据的文件。如果文件不存在,则创建一个新文件。
data
可选。规定要写入文件的数据。可以是字符串、数组或数据流。
mode
可选。规定如何打开/写入文件。可能的值:
- FILE_USE_INCLUDE_PATH
- FILE_APPEND
- LOCK_EX
context
可选。规定文件句柄的环境。
context 是一套可以修改流的行为的选项。若使用 null,则忽略。
注意事项:
- file_put_contents等于依次调用 fopen(),fwrite() 以及 fclose() 功能一样,但是效率要更高。
- data不仅仅是字符串,也包括数组格式和文本流,当是数组格式的时候(只能是一维数组,不能是多维数组),需要把数组分割implode(”, $array),其实还是转换为字符串,如果不分割的话文本存储的内容就是$array[0]$array[1]$array[2]$array[3]这种,不利于读取。文本流这个就更好理解了,例如存储file_get_contents(‘aa.jpg’)这一张图片的二进制流也是可以存储的。
- 模式:FILE_APPEND 是追加模式,默认的写入方式是覆盖之前的内容,但是使用FILE_APPEND 模式后就可以不覆盖之前的内容了。LOCK_EX是文本锁,防止并行写入冲突。
- context 和上面的file_get_contents一样,可以增加文本流选项,官方的一个例子