Stream in PHP)

Source: Internet
Author: User
Tags spl
Stream is one of the most overlooked function series (SPL series, Stream series, pack functions, and encapsulation protocols) in PHP development, but it is a very useful and important function. Stream can be translated as "Stream". in Java, Stream is a very important concept. The concept of stream is derived from the concept of pipe in UNIX. In UNIX, a media transcoding queue is an uninterrupted byte stream used for communication between programs or processes, or reading and writing peripheral devices and external files. Based on the direction of the stream, the stream can be divided into the input stream and the output stream. at the same time, other streams can be mounted on its periphery, such as the buffer stream, so that more stream processing methods can be obtained.

The stream in PHP is actually the same concept as the stream in Java, just a little simpler. Because PHP is mainly used for Web development, the concept of "stream" is rarely mentioned. With the Java Foundation, it is easier to understand the stream in PHP. In fact, many of the advanced features in PHP, such as SPL, exceptions, and filters, refer to the implementation of Java and share the same concept and principle.

For example, the following section describes the usage of the php spl standard library (traversing directories and searching for files with fixed conditions ):

Class RecursiveFileFilterIterator extends FilterIterator {// The qualified extension protected $ ext = array ('jpg ', 'GIF '); /*** provide $ path and generate the corresponding directory iterator */public function _ construct ($ path) {parent :: __construct (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ($ path);}/*** check whether the file extension meets the condition */public function accept () {$ item = $ this-> getInnerIterator (); if ($ item-> isFile () & in_array (pathinfo ($ item-> getFilename (), PATHINFO_EXTENSION ), $ this-> ext) {return TRUE ;}}// instantiate foreach (new RecursiveFileFilterIterator ('d:/history ') as $ item) {echo $ item. PHP_EOL ;}

Java also has the same code:

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());   } }}

For example, the concept of PHP and Java is the same in many aspects. mastering one language will be of great help to understanding another language. on the other hand, this example also helps the filter stream-filter mentioned below. It is also a manifestation of a design model.

We can use several examples to learn how to use stream functions.

The following is an example of using socket to capture data:

$ Post _ = array ('author' => 'gonn', 'mail' => 'gonn @ nowamagic.net ', 'URL' => 'http: // www.nowamagic.net /', 'text' => 'Welcome to modern magic'); $ data = http_build_query ($ post _); $ fp = fsockopen ("nowamagic.net", 80, $ errno, $ errstr, 5); $ out = "POST http://nowamagic.net/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 Fir Efox/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"; $ out. = $ data. "\ r \ n"; fwrite ($ fp, $ out); while (! Feof ($ fp) {echo fgets ($ fp, 1280);} fclose ($ fp );

We can also use stream_socket, which is very simple. you just need to switch the socket code to the following:

The code is as follows:


$ Fp = stream_socket_client ("tcp: // nowamagic.net: 80", $ errno, $ errstr, 3 );

Let's look at an example of stream:

The file_get_contents function is usually used to read the file content. However, this function can also be used to capture remote URLs and play a similar role as 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://nowamagic.net/news/1/comment', false, $context);

Note that the third parameter, $ context, is the HTTP stream context, can be understood as a pipe nested on the file_get_contents function. Similarly, we can also create FTP streams and socket streams and set them to the corresponding functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.