Last active
April 24, 2018 16:18
-
-
Save davebarnwell/427f1e58631c2cfe91e94c06b3e825aa to your computer and use it in GitHub Desktop.
get and put CSVs from a string instead of a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class StrCSV | |
public function strPutCsv($input, $delimiter = ',', $enclosure = '"') | |
{ | |
// Open a memory "file" for read/write... | |
$fp = fopen('php://memory', 'r+'); | |
// ... write the $input array to the "file" using fputcsv()... | |
fputcsv($fp, $input, $delimiter, $enclosure); | |
// ... rewind the "file" so we can read what we just wrote... | |
rewind($fp); | |
// ... read the entire line into a variable... | |
$data = fread($fp, 1048576); | |
// ... close the "file"... | |
fclose($fp); | |
// ... and return the $data to the caller, with the trailing newline from fgets() removed. | |
return rtrim($data, "\n"); | |
} | |
public function strGetCsv($input, $delimiter = ',', $enclosure = '"') | |
{ | |
// Open a memory "file" for read/write... | |
$fp = fopen('php://memory', 'r+'); | |
// ... write the $input string to the "file" using fputcsv()... | |
fwrite($fp, $input); | |
// ... rewind the "file" so we can read what we just wrote... | |
rewind($fp); | |
// ... read the entire line into an array variable... | |
$data = fgetcsv($fp, 1048576, $delimiter, $enclosure); | |
// ... close the "file"... | |
fclose($fp); | |
// ... and return the $data to the caller, with the trailing newline from fgets() removed. | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment