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

Support title-less CSVs #22

Merged
merged 2 commits into from
Nov 3, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
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; if missing, it will automatically assign field names (`field_1`, `field_2`, etc.); either `n` or `y` (default `y`)

Example Usage
-------------
Expand Down
23 changes: 19 additions & 4 deletions class.csv-to-api.php
Original file line number Diff line number Diff line change
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