php中stream(流)的用法

來源:互聯網
上載者:User

 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;}   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());        }    }}   舉這個例子,一方面是說明PHP和Java在很多方面的概念是一樣的,掌握一種語言對理解另外一門語言會有很大的協助;另一方面,這個例子也有助於我們下面要提到的過濾器流-filter。其實也是一種設計模式的體現。 我們可以通過幾個例子先來瞭解stream系列函數的使用。 下面是一個使用socket來抓取資料的例子: 代碼如下:$post_ =array ( 'author' => 'Gonn', 'mail'=>'gonn@nowamagic.net', 'url'=>'http://www.nowamagic.net/', 'text'=>'歡迎訪問簡明現代魔法'); $data=http_build_query($post_);$fp = fsockopen("nowamagic.net", 80, $errno, $errstr, 5); $out="POST http://nowamagic.net/news/1/comment HTTP/1.1rn";$out.="Host: typecho.orgrn";$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"."rn";$out.="Content-type: application/x-www-form-urlencodedrn";$out.="PHPSESSID=082b0cc33cc7e6df1f87502c456c3eb0rn";$out.="Content-Length: " . strlen($data) . "rn";$out.="Connection: closernrn";$out.=$data."rnrn"; fwrite($fp, $out);while (!feof($fp)){    echo fgets($fp, 1280);} fclose($fp);   我們也可以用stream_socket 實現,這很簡單,只需要開啟socket的代碼換成下面的即可:  代碼如下:$fp = stream_socket_client("tcp://nowamagic.net:80", $errno, $errstr, 3);  再來看一個stream的例子: file_get_contents函數一般常用來讀取檔案內容,但這個函數也可以用來抓取遠程url,起到和curl類似的作用。  代碼如下:$opts = array ( 'http'=>array(    'method' => 'POST',    'header'=> "Content-type: application/x-www-form-urlencodedrn" .      "Content-Length: " . strlen($data) . "rn",    'content' => $data)); $context = stream_context_create($opts);file_get_contents('http://www.jb51.net/news', false, $context);   注意第三個參數,$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))));  一層流嵌套著另外一層流,和PHP裡有異曲同工之妙。 我們再來看個過濾器流的作用: 代碼如下:$fp = fopen('c:/test.txt', 'w+'); /* 把rot13過濾器作用在寫入流上 */stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE); /* 寫入的資料經過rot13過濾器的處理*/fwrite($fp, "This is a testn");rewind($fp); /* 讀取寫入的資料,獨到的自然是被處理過的字元了 */fpassthru($fp);fclose($fp); // output:Guvf vf n grfg   在上面的例子中,如果我們把過濾器的類型設定為STREAM_FILTER_ALL,即同時作用在讀寫流上,那麼讀寫的資料都將被rot13過濾器處理,我們讀出的資料就和寫入的未經處理資料是一致的。 你可能會奇怪stream_filter_append中的 "string.rot13"這個變數來的莫名其妙,這實際上是PHP內建的一個過濾器。 使用下面的方法即可列印出PHP內建的流: 代碼如下:streamlist = stream_get_filters();print_r($streamlist);  輸出:  代碼如下: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.*)  自然而然,我們會想到定義自己的過濾器,這個也不難: 代碼如下: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");   注意:過濾器名可以隨意取。 之後就可以使用"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")."rn");};   這個過濾器不僅可以對輸入資料流進行處理,還能回調一個函數來進行日誌記錄。 可以這麼使用:  代碼如下:stream_filter_prepend($fp, "string.md5", STREAM_FILTER_WRITE,$callback);  PHP中的stream流系列函數中還有一個很重要的流,就是封裝類流 streamWrapper。使用封裝流可以使得不同類型的協議使用相同的介面操縱資料。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.