diff --git a/README.md b/README.md index a5e23d8..73de54b 100644 --- a/README.md +++ b/README.md @@ -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; if missing, it will automatically assign field names (`field_1`, `field_2`, etc.); either `n` or `y` (default `y`) Example Usage ------------- diff --git a/class.csv-to-api.php b/class.csv-to-api.php index 601038d..a312562 100644 --- a/class.csv-to-api.php +++ b/class.csv-to-api.php @@ -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