My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

/**
* Example to dumping data into a CSV file using Stream_Iterate as stream
*
* PHP version 5.3+
*
* @category Stream
* @package Stream_Iterate
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @copyright 2008 11abacus / Philippe Jausions
* @license http://www.opensource.org/licenses/bsd-license.php New BSD
* @link http://pear.11abacus.com/package/Stream_Iterate
*/

if (version_compare(phpversion(), '5.3.0', '<')) {
echo 'Stream contexts are not supported in copy() with your version of PHP.';
exit;
}

/**
* Required packages
*/
require_once 'Stream/Iterate.php';
require_once 'System/Folders.php';

/**
* Defines a CSV "printer"
*
* @param array $value list of data to print out
*
* @return string the CSV string
*/
function toString(array $value)
{
static $headers;

$result = '';
if (!isset($headers)) {
$headers = array_keys($value);
$result = implode(',', $headers)."\n";
}
foreach ($headers as $header) {
$result .= '"'.str_replace('"', '""', $value[$header]).'",';
}

return substr($result, 0, -1)."\n";
}

/**
* Main
*/
stream_wrapper_register('foreach', 'Stream_Iterate');

$data = array(array('firstname' => 'John',
'lastname' => 'Doe',
'city' => 'Towneville'),
array('lastname' => 'Doe',
'city' => 'Citybourg',
'firstname' => 'Jane'));

$context = stream_context_create(array('foreach' => array('data' => $data)));

$sf = new System_Folders();

$tempFile = tempnam($sf->getTemp(), 'MyFile');

// Context support for copy() was added in 5.3.0
copy('foreach://value@data?toString=toString', $tempFile, $context);

echo 'Data copied to '.$tempFile;

?>

Change log

r7 by jausions on May 13, 2008   Diff
+ Added 2 tests
+ Updated license URL
Go to: 
Project members, sign in to write a code review

Older revisions

r5 by jausions on May 13, 2008   Diff
 + Created a FormatterInterface to
encapsulate formatting methods
 + Added examples
 + Rename "callback" context option to
"toString"
...
r3 by jausions on May 1, 2008   Diff
Initial check in
All revisions of this file

File info

Size: 1794 bytes, 73 lines
Powered by Google Project Hosting