溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

stream(流)如何在php中使用

發(fā)布時間:2021-01-05 15:20:58 來源:億速云 閱讀:175 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了stream(流)如何在php中使用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

在Java里,流是一個很重要的概念。

流(stream)的概念源于UNIX中管道(pipe)的概念。在UNIX中,管道是一條不間斷的字節(jié)流,用來實(shí)現(xiàn)程序或進(jìn)程間的通信,或讀寫外圍設(shè)備、外部文件等。根據(jù)流的方向又可以分為輸入流和輸出流,同時可以在其外圍再套上其它流,比如緩沖流,這樣就可以得到更多流處理方法。

PHP里的流和Java里的流實(shí)際上是同一個概念,只是簡單了一點(diǎn)。由于PHP主要用于Web開發(fā),所以“流”這塊的概念被提到的較少。如果有Java基礎(chǔ),對于PHP里的流就更容易理解了。其實(shí)PHP里的許多高級特性,比如SPL,異常,過濾器等都參考了Java的實(shí)現(xiàn),在理念和原理上同出一轍。

比如下面是一段PHP SPL標(biāo)準(zhǔn)庫的用法(遍歷目錄,查找固定條件的文件):

復(fù)制代碼 代碼如下:


class RecursiveFileFilterIterator extends FilterIterator
{
    // 滿足條件的擴(kuò)展名
    protected $ext = array('jpg','gif');

    /**
     * 提供 $path 并生成對應(yīng)的目錄迭代器
     */
    public function __construct($path)
    {
        parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
    }

    /**
     * 檢查文件擴(kuò)展名是否滿足條件
     */
    public function accept()
    {
        $item = $this->getInnerIterator();
        if ($item->isFile() && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext))
        {
            return TRUE;
        }
    }
}

// 實(shí)例化
foreach (new RecursiveFileFilterIterator('D:/history') as $item)
{
    echo $item . PHP_EOL;
}

Java里也有和其同出一轍的代碼:

復(fù)制代碼 代碼如下:


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。其實(shí)也是一種設(shè)計模式的體現(xiàn)。

我們可以通過幾個例子先來了解stream系列函數(shù)的使用。

下面是一個使用socket來抓取數(shù)據(jù)的例子:

復(fù)制代碼 代碼如下:


$post_ =array (
 'author' => 'Gonn',
 'mail'=>'gonn@nowamagic.net',
 'url'=>'http://www.nowamagic.net/',
 'text'=>'歡迎訪問簡明現(xiàn)代魔法');

$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\r\n";
$out.=$data."\r\n\r\n";

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

fclose($fp);

我們也可以用stream_socket 實(shí)現(xiàn),這很簡單,只需要打開socket的代碼換成下面的即可:

復(fù)制代碼 代碼如下:


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

再來看一個stream的例子:

file_get_contents函數(shù)一般常用來讀取文件內(nèi)容,但這個函數(shù)也可以用來抓取遠(yuǎn)程url,起到和curl類似的作用。

復(fù)制代碼 代碼如下:


$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('https://www.jb51.net/news', false, $context);

注意第三個參數(shù),$context,即HTTP流上下文,可以理解為套在file_get_contents函數(shù)上的一根管道。同理,我們還可以創(chuàng)建FTP流,socket流,并把其套在對應(yīng)的函數(shù)在。

更多關(guān)于 stream_context_create,可以參考:PHP函數(shù)補(bǔ)完:stream_context_create()模擬POST/GET。

上面提到的兩個stream系列的函數(shù)都是類似包裝器的流,作用在某種協(xié)議的輸入輸出流上。這樣的使用方式和概念,其實(shí)和Java中的流并沒有大的區(qū)別,比如Java中經(jīng)常有這樣的寫法:

復(fù)制代碼 代碼如下:


new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(fileName))));

一層流嵌套著另外一層流,和PHP里有異曲同工之妙。

我們再來看個過濾器流的作用:

復(fù)制代碼 代碼如下:


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

/* 把rot13過濾器作用在寫入流上 */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* 寫入的數(shù)據(jù)經(jīng)過rot13過濾器的處理*/
fwrite($fp, "This is a test\n");
rewind($fp);

/* 讀取寫入的數(shù)據(jù),獨(dú)到的自然是被處理過的字符了 */
fpassthru($fp);
fclose($fp);

// output:Guvf vf n grfg

在上面的例子中,如果我們把過濾器的類型設(shè)置為STREAM_FILTER_ALL,即同時作用在讀寫流上,那么讀寫的數(shù)據(jù)都將被rot13過濾器處理,我們讀出的數(shù)據(jù)就和寫入的原始數(shù)據(jù)是一致的。

你可能會奇怪stream_filter_append中的 "string.rot13"這個變量來的莫名其妙,這實(shí)際上是PHP內(nèi)置的一個過濾器。

使用下面的方法即可打印出PHP內(nèi)置的流:

復(fù)制代碼 代碼如下:


streamlist = stream_get_filters();
print_r($streamlist);

輸出:

復(fù)制代碼 代碼如下:


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.*
)

自然而然,我們會想到定義自己的過濾器,這個也不難:

復(fù)制代碼 代碼如下:


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

        //數(shù)據(jù)處理成功,可供其它管道讀取
        return PSFS_PASS_ON;
    }
}
stream_filter_register("string.md5", "md5_filter");

注意:過濾器名可以隨意取。

之后就可以使用"string.md5"這個我們自定義的過濾器了。

這個過濾器的寫法看起來很是有點(diǎn)摸不著頭腦,事實(shí)上我們只需要看一下php_user_filter這個類的結(jié)構(gòu)和內(nèi)置方法即了解了。

過濾器流最適合做的就是文件格式轉(zhuǎn)換了,包括壓縮,編解碼等,除了這些“偏門”的用法外,filter流更有用的一個地方在于調(diào)試和日志功能,比如說在socket開發(fā)中,注冊一個過濾器流進(jìn)行l(wèi)og記錄。比如下面的例子:

復(fù)制代碼 代碼如下:


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

這個過濾器不僅可以對輸入流進(jìn)行處理,還能回調(diào)一個函數(shù)來進(jìn)行日志記錄。

可以這么使用:

復(fù)制代碼 代碼如下:


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

PHP中的stream流系列函數(shù)中還有一個很重要的流,就是包裝類流 streamWrapper。使用包裝流可以使得不同類型的協(xié)議使用相同的接口操縱數(shù)據(jù)。

上述內(nèi)容就是stream(流)如何在php中使用,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI