Skip to content
This repository has been archived by the owner on Sep 22, 2021. It is now read-only.

Commit

Permalink
Support CSVs without column titles
Browse files Browse the repository at this point in the history
Automatically generate field names when column titles are missing, as
specified by a URL parameter.
  • Loading branch information
waldoj committed Mar 11, 2014
1 parent 9de7f1c commit 6a6e80a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -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
-------------
Expand Down
23 changes: 19 additions & 4 deletions class.csv-to-api.php
Expand Up @@ -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 );

}
Expand All @@ -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.
Expand All @@ -66,7 +68,6 @@ function parse() {
$this->data = $this->curl_get( $this->source );
}


if ( !$this->data ) {
header( '502 Bad Gateway' );
die( 'Bad data source' );
Expand Down Expand Up @@ -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 ) {

Expand Down

0 comments on commit 6a6e80a

Please sign in to comment.