Home  >  Article  >  Backend Development  >  理解 PHP 中的 Streams_PHP教程

理解 PHP 中的 Streams_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:53:02837browse

理解 PHP 中的 Streams

   Streams 是PHP提供的一个强有力的工具,我们常常在不经意会使用到它,如果善加利用将大大提高PHP的生产力。 驾驭Streams的强大力量后,应用程序将提升到一个新的高度。

  下面是PHP手册中对Streams的一段描述:

  Streams 是在PHP 4.3.0版本被引入的,它被用于统一文件、网络、数据压缩等类文件的操作方式,为这些类文件操作提供了一组通用的函数接口。简而言之,一个stream就是一个具有流式行为的资源对象。也就是说,我们可以用线性的方式来对stream进行读取和写入。并且可以用使用fseek()来跳转到stream内的任意位置。

  每个Streams对象都有一个包装类,在包装中可以添加处理特殊协议和编码的相关代码。PHP中已经内置了一些常用的包装类,我们也可以创建和注册自定义的包装类。我们甚至能够使用现有的context和filter对包装类进行修改和增强。

  Stream 基础知识

  Stream 可以通过://方式来引用。其中是包装类的名字,中的内容是由包装类的语法指定,不同的包装类的语法会有所不同。

  PHP默认的包装类是file://,也就是说我们在访问文件系统的时候,其实就是在使用一个stream。我们可以通过下面两种方式来读取文件中的内容,readfile('/path/to/somefile.txt')或者readfile('file:///path/to/somefile.txt'),这两种方式是等效的。如果你是使用readfile('http://google.com/'),那么PHP会选取HTTP stream包装类来进行操作。

  正如上文所述,PHP提供了不少内建的包转类,protocol以及filter。 按照下文所述的方式,可以查询到本机所支持的包装类:

  

  print_r(stream_get_transports());

  print_r(stream_get_wrappers());

  print_r(stream_get_filters());

  在我机器上的输出结果为:

  Array

  (

  [0] => tcp

  [1] => udp

  [2] => unix

  [3] => udg

  [4] => ssl

  [5] => sslv3

  [6] => sslv2

  [7] => tls

  )

  Array

  (

  [0] => https

  [1] => ftps

  [2] => compress.zlib

  [3] => compress.bzip2

  [4] => php

  [5] => file

  [6] => glob

  [7] => data

  [8] => http

  [9] => ftp

  [10] => zip

  [11] => phar

  )

  Array

  (

  [0] => zlib.*

  [1] => bzip2.*

  [2] => convert.iconv.*

  [3] => string.rot13

  [4] => string.toupper

  [5] => string.tolower

  [6] => string.strip_tags

  [7] => convert.*

  [8] => consumed

  [9] => dechunk

  [10] => mcrypt.*

  [11] => mdecrypt.*

  )

  提供的功能非常多,看上去还不错吧?

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1004546.htmlTechArticle理解 PHP 中的 Streams Streams 是PHP提供的一个强有力的工具,我们常常在不经意会使用到它,如果善加利用将大大提高PHP的生产力。 驾驭Stre...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn