Permalink
Browse files

Support CSVs without column titles

Automatically generate field names when column titles are missing, as
specified by a URL parameter.
  • Loading branch information...
1 parent 9de7f1c commit 6a6e80a871497ebdfd675563c2df2dc003707c78 @waldoj waldoj committed Mar 11, 2014
Showing with 20 additions and 4 deletions.
  1. +1 −0 README.md
  2. +19 −4 class.csv-to-api.php
View
@@ -39,6 +39,7 @@ Arguments
* `sort`: field to sort by (optional)
* `sort_dir`: direction to sort, either `asc` or `desc` (default `asc`)
* any field(s): may pass any fields as a key/value pair to filter by
+* `header_row`: whether the source CSV has a header row (default `y`); if missing, it will automatically assign field names (`field_1`, `field_2`, etc.)
Example Usage
-------------
View
@@ -34,7 +34,8 @@ function parse_query( $query = null ) {
$this->callback = isset( $query['callback'] ) ? $this->jsonp_callback_filter( $query['callback'] ) : false;
$this->sort = isset( $query['sort'] ) ? $query['sort'] : null;
$this->sort_dir = isset( $query['sort_dir'] ) ? $query['sort_dir'] : "desc";
-
+ $this->header_row = isset( $query['header_row'] ) ? $query['header_row'] : "y";
+
return get_object_vars( $this );
}
@@ -56,6 +57,7 @@ function parse() {
// Attempt to retrieve the data from cache
$key = 'csv_to_api_' . md5( $this->source );
$this->data = $this->get_cache( $key );
+
if ( !$this->data ) {
// Retrieve the requested source material via HTTP GET.
@@ -66,7 +68,6 @@ function parse() {
$this->data = $this->curl_get( $this->source );
}
-
if ( !$this->data ) {
header( '502 Bad Gateway' );
die( 'Bad data source' );
@@ -175,8 +176,22 @@ function parse_csv( $csv ) {
$lines = explode( "\n", $csv );
$lines = $this->parse_lines( $lines );
-
- $headers = array_shift( $lines );
+
+ // If no header row exists, automatically create field names.
+ if ($this->header_row == 'n') {
+
+ for ($i=0; $i<count($lines[0]); $i++)
+ {
+ $headers[$i] = 'field-' . ($i+1);
+ }
+
+ }
+
+ // If a header row exists, use that as the headers.
+ else {
+ $headers = array_shift( $lines );
+ }
+
$data = array();
foreach ( $lines as $line ) {

0 comments on commit 6a6e80a

Please sign in to comment.