1: <?php
2: 3: 4: 5:
6:
7: namespace Httpful\Handlers;
8:
9: class CsvHandler extends MimeHandlerAdapter
10: {
11: 12: 13: 14: 15:
16: public function parse($body)
17: {
18: if (empty($body))
19: return null;
20:
21: $parsed = array();
22: $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
23: while (($r = fgetcsv($fp)) !== FALSE) {
24: $parsed[] = $r;
25: }
26:
27: if (empty($parsed))
28: throw new \Exception("Unable to parse response as CSV");
29: return $parsed;
30: }
31:
32: 33: 34: 35:
36: public function serialize($payload)
37: {
38: $fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+');
39: $i = 0;
40: foreach ($payload as $fields) {
41: if($i++ == 0) {
42: fputcsv($fp, array_keys($fields));
43: }
44: fputcsv($fp, $fields);
45: }
46: rewind($fp);
47: $data = stream_get_contents($fp);
48: fclose($fp);
49: return $data;
50: }
51: }
52: