Usage of stream in php _ php instance

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". The following is a very important concept of Stream in Java.

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 ):

The Code is as follows:


Class RecursiveFileFilterIterator extends FilterIterator
{
// The extension that meets the condition
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 conditions
*/
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:

The Code is as follows:


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:

The Code is as follows:


$ 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 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 ";
$ 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.

The Code is as follows:


$ 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: // www.php.net/news', 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.