Permalink
Browse files

Supporting different types of newlines.

Only \n (Unix) newlines were supported. The use of \r (nominally old
Macintosh) is widespread, and failed on the first government-generated
CSV file that I tried. Also common are \r\n (Windows) newlines. This
will determine which type of newline is most common in the file and
default to that.
  • Loading branch information...
1 parent a69d750 commit 669a326535a087f7b3e105690e4be351713afb08 @waldoj waldoj committed Jan 1, 2013
Showing with 12 additions and 2 deletions.
  1. +12 −2 class.csv-to-api.php
View
@@ -47,6 +47,7 @@ function parse() {
// Create an instance of the parser for the requested file format (e.g. CSV)
$parser = 'parse_' . $this->source_format;
+
if ( !method_exists( $this, $parser ) ) {
header( '400 Bad Request' );
die( 'Format not supported' );
@@ -156,8 +157,17 @@ function xml_entities( $string ) {
* Turn CSV into a PHP array.
*/
function parse_csv( $csv ) {
-
- $lines = explode( "\n", $csv );
+ if ( substr_count($csv, "\n" ) > substr_count($csv, "\r" ) )
+ {
+ $newline = "\n";
+ }
+ else
+ {
+ $newline = "\r";
+ }
+
+ $lines = explode( $newline, $csv );
+
$headers = str_getcsv( array_shift( $lines ) );
$data = array();
foreach ( $lines as $line ) {

0 comments on commit 669a326

Please sign in to comment.