2014年5月28日 星期三

[PHP] stream resource output

最近看到有一段代碼是要輸出 CSV 檔案:

$rows = array();
$rows[] = array(1,2,3,"四");

ob_start();
$fh = fopen("php://output", "w");
foreach ($rows as $r) {
   fputcsv($fh, $r);
}
fclose($fh);
$csv = ob_get_clean();

var_dump($csv);

從上述代碼看到,轉換的方式是使用 Output Control Functions。

其實這麼寫並不妥當。整段代碼被 ob 給限制住了,如果還要做一些錯誤處理,會使得代碼變得相當複雜。 而且個人相當排斥使用 ob。

有寫過 Java 應該都會先想到 java.io 提供的 InputStream。 所以試著查詢 PHP Manual,找到相似的方法,重新改寫一下:

$rows = array();
$rows[] = array(1,2,3,"四");

$fh = fopen("php://temp", "w+");
foreach ($rows as $r) {
   fputcsv($fh, $r);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);

var_dump($csv);

去掉 ob 之後,整個資料流就都在 stream resource 處理,看起來會比較適當。 日後有需要修改或除錯也都變得比較容易多。

參考資料:http://www.php.net/manual/en/function.stream-get-contents.php

PHP 5.3.24 (cli) (built: Jun 10 2013 16:42:20)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...