Last active
October 19, 2017 08:18
-
-
Save zsteva/03c78c25c937403ac5bf23811af25768 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| function excell_arr2csv($header, $data) { | |
| $line = ''; | |
| foreach ($header as $field) { | |
| $d = isset($data[$field]) ? $data[$field] : ''; | |
| $d = str_replace("\n", " ", $d); | |
| $d = str_replace('"', '""', $d); | |
| # http://georgemauer.net/2017/10/07/csv-injection.html | |
| if (in_array(substr($d, 0, 1), ['=', '-', '+', '@'], true)) { | |
| $d = "\t" . $d; | |
| } | |
| if ($line != '') $line .= ','; | |
| $line .= '"' . $d . '"'; | |
| } | |
| return $line; | |
| } | |
| function excell_csv_output($output_file, $header, $data) { | |
| $fp = fopen($output_file, "w+"); | |
| fwrite($fp, "\xEF\xBB\xBF"); | |
| $header_keys = array_keys($header); | |
| fwrite($fp, excell_arr2csv($header_keys, $header) . "\r\n"); | |
| foreach ($data as $row) { | |
| fwrite($fp, excell_arr2csv($header_keys, $row) . "\r\n"); | |
| } | |
| fclose($fp); | |
| } | |
This file contains hidden or 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 | |
| include_once dirname(__FILE__) . '/excell-csv-output.php'; | |
| $output_file = "t1.csv"; | |
| $header = array('a' => 'a', 'b' => 'b'); | |
| $data = [ | |
| ['a' => 'aaa', 'b' => '4+4'], | |
| ['a' => 'bbb', 'b' => '=4+4'], | |
| ['a' => 'ccc', 'b' => ''], | |
| ]; | |
| excell_csv_output($output_file, $header, $data); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment