Home php教程 php手册 了解PHP中Stream(流)的概念与用法

了解PHP中Stream(流)的概念与用法

Jun 13, 2016 am 09:39 AM
stream filter

Stream是PHP开发里最容易被忽视的函数系列(SPL系列,Stream系列,pack函数,封装协议)之一,但其是个很有用也很重要的函数。Stream可以翻译为“流”,在Java里,流是一个很重要的概念。

流(stream)的概念源于UNIX中管道(pipe)的概念。在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备、外部文件等。根据流的方向又可以分为输入流和输出流,同时可以在其外围再套上其它流,比如缓冲流,这样就可以得到更多流处理方法。

PHP里的流和Java里的流实际上是同一个概念,只是简单了一点。由于PHP主要用于Web开发,所以“流”这块的概念被提到的较少。如果有Java基础,对于PHP里的流就更容易理解了。其实PHP里的许多高级特性,比如SPL,异常,过滤器等都参考了Java的实现,在理念和原理上同出一辙。

比如下面是一段PHP SPL标准库的用法(遍历目录,查找固定条件的文件):

class RecursiveFileFilterIterator extends FilterIterator
{
    // 满足条件的扩展名
    protected $ext = array('jpg','gif');

    /**
     * 提供 $path 并生成对应的目录迭代器
     */
    public function __construct($path)
    {
        parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
    }

    /**
     * 检查文件扩展名是否满足条件
     */
    public function accept()
    {
        $item = $this->getInnerIterator();
        if ($item->isFile() && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext))
        {
            return TRUE;
        }
    }
}

// 实例化
foreach (new RecursiveFileFilterIterator('D:/history') as $item)
{
    echo $item . PHP_EOL;
}
Copy after login

Java里也有和其同出一辙的代码:

public class DirectoryContents
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("."); // current directory

        FilenameFilter textFilter = new FilenameFilter()
        {
            public boolean accept(File dir, String name)
            {
                String lowercaseName = name.toLowerCase();
                if (lowercaseName.endsWith(".txt"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        };

        File[] files = f.listFiles(textFilter);

        for (File file : files)
        {
            if (file.isDirectory())
            {
                System.out.print("directory:");
            }
            else
            {
                System.out.print("     file:");
            }

            System.out.println(file.getCanonicalPath());
        }
    }
}
Copy after login

举这个例子,一方面是说明PHP和Java在很多方面的概念是一样的,掌握一种语言对理解另外一门语言会有很大的帮助;另一方面,这个例子也有助于我们下面要提到的过滤器流-filter。其实也是一种设计模式的体现。

我们可以通过几个例子先来了解stream系列函数的使用。

下面是一个使用socket来抓取数据的例子:

$post_ =array (
	'author' => 'Gonn',
	'mail'=>'gonn@bkjia.com',
	'url'=>'http://www.bkjia.com/',
	'text'=>'欢迎访问帮客之家');

$data=http_build_query($post_);
$fp = fsockopen("bkjia.com", 80, $errno, $errstr, 5);

$out="POST http://bkjia.com/news/1/comment HTTP/1.1\r\n";
$out.="Host: typecho.org\r\n";
$out.="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"."\r\n";
$out.="Content-type: application/x-www-form-urlencoded\r\n";
$out.="PHPSESSID=082b0cc33cc7e6df1f87502c456c3eb0\r\n";
$out.="Content-Length: " . strlen($data) . "\r\n";
$out.="Connection: close\r\n\r\n";
$out.=$data."\r\n\r\n";

fwrite($fp, $out);
while (!feof($fp))
{
    echo fgets($fp, 1280);
}

fclose($fp);
Copy after login

我们也可以用stream_socket 实现,这很简单,只需要打开socket的代码换成下面的即可:

$fp = stream_socket_client("tcp://bkjia.com:80", $errno, $errstr, 3);
Copy after login

再来看一个stream的例子:

file_get_contents函数一般常用来读取文件内容,但这个函数也可以用来抓取远程url,起到和curl类似的作用。

$opts = array (
	'http'=>array(
	   'method' => 'POST',
	   'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .
				  "Content-Length: " . strlen($data) . "\r\n",
	   'content' => $data)
);

$context = stream_context_create($opts);
file_get_contents('http://bkjia.com/news/1/comment', false, $context);
Copy after login

注意第三个参数,$context,即HTTP流上下文,可以理解为套在file_get_contents函数上的一根管道。同理,我们还可以创建FTP流,socket流,并把其套在对应的函数在。

更多关于 stream_context_create,可以参考:PHP函数补完:stream_context_create()模拟POST/GET。

上面提到的两个stream系列的函数都是类似包装器的流,作用在某种协议的输入输出流上。这样的使用方式和概念,其实和Java中的流并没有大的区别,比如Java中经常有这样的写法:

new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(fileName))));
Copy after login

一层流嵌套着另外一层流,和PHP里有异曲同工之妙。

我们再来看个过滤器流的作用:

$fp = fopen('c:/test.txt', 'w+');

/* 把rot13过滤器作用在写入流上 */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* 写入的数据经过rot13过滤器的处理*/
fwrite($fp, "This is a test\n");
rewind($fp);

/* 读取写入的数据,独到的自然是被处理过的字符了 */
fpassthru($fp);
fclose($fp);

// output:Guvf vf n grfg
Copy after login

在上面的例子中,如果我们把过滤器的类型设置为STREAM_FILTER_ALL,即同时作用在读写流上,那么读写的数据都将被rot13过滤器处理,我们读出的数据就和写入的原始数据是一致的。

你可能会奇怪stream_filter_append中的 "string.rot13"这个变量来的莫名其妙,这实际上是PHP内置的一个过滤器。

使用下面的方法即可打印出PHP内置的流:

$streamlist = stream_get_filters();
print_r($streamlist);
Copy after login

输出:

Array
(
    [0] => convert.iconv.*
    [1] => mcrypt.*
    [2] => mdecrypt.*
    [3] => string.rot13
    [4] => string.toupper
    [5] => string.tolower
    [6] => string.strip_tags
    [7] => convert.*
    [8] => consumed
    [9] => dechunk
    [10] => zlib.*
    [11] => bzip2.*
)
Copy after login

自然而然,我们会想到定义自己的过滤器,这个也不难:

class md5_filter extends php_user_filter
{
    function filter($in, $out, &$consumed, $closing)
    {
        while ($bucket = stream_bucket_make_writeable($in))
        {
            $bucket->data = md5($bucket->data);
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }

        //数据处理成功,可供其它管道读取
        return PSFS_PASS_ON;
    }
}

stream_filter_register("string.md5", "md5_filter");
Copy after login

注意:过滤器名可以随意取。

之后就可以使用"string.md5"这个我们自定义的过滤器了。

这个过滤器的写法看起来很是有点摸不着头脑,事实上我们只需要看一下php_user_filter这个类的结构和内置方法即了解了。

过滤器流最适合做的就是文件格式转换了,包括压缩,编解码等,除了这些“偏门”的用法外,filter流更有用的一个地方在于调试和日志功能,比如说在socket开发中,注册一个过滤器流进行log记录。比如下面的例子:

class md5_filter extends php_user_filter
{
    public function filter($in, $out, &$consumed, $closing)
    {
        $data="";
        while ($bucket = stream_bucket_make_writeable($in))
        {
            $bucket->data = md5($bucket->data);
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }

        call_user_func($this->params, $data);
        return PSFS_PASS_ON;
    }
}

$callback = function($data)
{
    file_put_contents("c:\log.txt",date("Y-m-d H:i")."\r\n");
};
Copy after login

这个过滤器不仅可以对输入流进行处理,还能回调一个函数来进行日志记录。

可以这么使用:

stream_filter_prepend($fp, "string.md5", STREAM_FILTER_WRITE,$callback);
Copy after login

PHP中的stream流系列函数中还有一个很重要的流,就是包装类流 streamWrapper。使用包装流可以使得不同类型的协议使用相同的接口操纵数据。这个以后再说。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to debug Java Stream operations in IntelliJ IDEA How to debug Java Stream operations in IntelliJ IDEA May 09, 2023 am 11:25 AM

Stream operation is a highlight of Java8! Although java.util.stream is very powerful, there are still many developers who rarely use it in actual work. One of the most complained reasons is that it is difficult to debug. This was indeed the case at the beginning, because streaming operations such as stream cannot be used in DEBUG When it is one line of code, when it comes to the next step, many operations are actually passed at once, so it is difficult for us to judge which line in it is the problem. Plug-in: JavaStreamDebugger If the IDEA version you are using is relatively new, this plug-in is already included and does not need to be installed. If it is not installed yet, install it manually and then continue below.

How to get max value from stream in java8 How to get max value from stream in java8 May 14, 2023 pm 03:43 PM

java8's stream takes maxpublicstaticvoidmain(String[]args){Listlist=Arrays.asList(1,2,3,4,5,6);Integermax=list.stream().max((a,b)->{if (a>b){return1;}elsereturn-1;}).get();System.out.println(max);}Note: The size is determined here through positive and negative numbers and 0 values. Instead of writing it directly if(a>b){returna;}elseretur

Vue error: The filter in filters cannot be used correctly, how to solve it? Vue error: The filter in filters cannot be used correctly, how to solve it? Aug 26, 2023 pm 01:10 PM

Vue error: The filter in filters cannot be used correctly, how to solve it? Introduction: In Vue, filters are a commonly used function that can be used to format or filter data. However, during use, sometimes we may encounter problems with not being able to use the filter correctly. This article will cover some common causes and solutions. 1. Cause analysis: The filter is not registered correctly: Filters in Vue need to be registered before they can be used in templates. If the filter is not successfully registered,

What does stream mean in linux? What does stream mean in linux? Mar 17, 2023 am 09:55 AM

In Linux, stream means data flow, which is a string of data read in a certain order, so the direction of the data flow is the reading order of the data flow. The process of the Linux system importing the output results after reading the data into other files is called redirected data flow. After a command is entered and run under Linux, two results will be displayed on the screen: the result of a successful operation is the standard output, and the result of a failed operation is the standard error output; if not processed, they will be displayed on the screen and redirected through the data stream. You can save it to other files.

How to filter and sort data in Vue technology development How to filter and sort data in Vue technology development Oct 09, 2023 pm 01:25 PM

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs Sep 14, 2023 am 10:37 AM

The FILTER_VALIDATE_URL constant is used to validate URLs. The flag FILTER_FLAG_SCHEME_REQUIRED−URL must be RFC compliant. FILTER_FLAG_HOST_REQUIRED−URL must contain the hostname. FILTER_FLAG_PATH_REQUIRED−URL must have a path after the domain name. FILTER_FLAG_QUERY_REQUIRED−URL must have a query string. Return value FILTER_VALIDATE_URL

Filter function in Vue3: handle data elegantly Filter function in Vue3: handle data elegantly Jun 18, 2023 pm 02:46 PM

Filter Functions in Vue3: Handling Data Elegantly Vue is a popular JavaScript framework with a large community and a powerful plug-in system. In Vue, the filter function is a very practical tool that allows us to process and format data in templates. There have been some changes to the filter functions in Vue3. In this article, we will take a deep dive into the filter functions in Vue3 and learn how to use them to handle data gracefully. What is a filter function? In Vue, the filter function is

PHP Email Filter: Filter and identify spam. PHP Email Filter: Filter and identify spam. Sep 19, 2023 pm 12:51 PM

PHP Email Filter: Filter and identify spam. With the widespread use of email, the amount of spam has also continued to increase. For users, the amount of spam they receive can lead to information overload and wasted time. Therefore, we need an efficient method to filter and identify spam emails. This article will show you how to write a simple but effective email filter using PHP and provide specific code examples. Basic Principle of Email Filter The basic principle of email filter is to determine whether the email is

See all articles