Overview

Namespaces

  • Httpful
    • Exception
    • Handlers
    • Response
  • PHP

Classes

  • Closure
  • XMLWriter

Interfaces

  • ArrayAccess
  • Countable
  • Exception
  • Overview
  • Namespace
  • Class
 1: <?php
 2: /**
 3:  * Mime Type: text/csv
 4:  * @author Raja Kapur <rajak@twistedthrottle.com>
 5:  */
 6: 
 7: namespace Httpful\Handlers;
 8: 
 9: class CsvHandler extends MimeHandlerAdapter
10: {
11:     /**
12:      * @param string $body
13:      * @return mixed
14:      * @throws \Exception
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:      * @param mixed $payload
34:      * @return string
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: 
API documentation generated by ApiGen