Fix for parseCSV constructor error

This commit is contained in:
Hillel Coren 2016-10-28 14:35:32 +03:00
parent bd624710a8
commit 346dde8e97

View File

@ -1,21 +1,21 @@
<?php <?php
class parseCSV { class parseCSV {
/* /*
Class: parseCSV v0.3.2 Class: parseCSV v0.3.2
http://code.google.com/p/parsecsv-for-php/ http://code.google.com/p/parsecsv-for-php/
Fully conforms to the specifications lined out on wikipedia: Fully conforms to the specifications lined out on wikipedia:
- http://en.wikipedia.org/wiki/Comma-separated_values - http://en.wikipedia.org/wiki/Comma-separated_values
Based on the concept of Ming Hong Ng's CsvFileParser class: Based on the concept of Ming Hong Ng's CsvFileParser class:
- http://minghong.blogspot.com/2006/07/csv-parser-for-php.html - http://minghong.blogspot.com/2006/07/csv-parser-for-php.html
Copyright (c) 2007 Jim Myhrberg (jim@zydev.info). Copyright (c) 2007 Jim Myhrberg (jim@zydev.info).
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
@ -35,9 +35,9 @@ class parseCSV {
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
Code Examples Code Examples
---------------- ----------------
# general usage # general usage
@ -74,7 +74,7 @@ class parseCSV {
$csv = new parseCSV(); $csv = new parseCSV();
$csv->output (true, 'movies.csv', $array); $csv->output (true, 'movies.csv', $array);
---------------- ----------------
*/ */
@ -83,87 +83,87 @@ class parseCSV {
* Configuration * Configuration
* - set these options with $object->var_name = 'value'; * - set these options with $object->var_name = 'value';
*/ */
# use first line/entry as field names # use first line/entry as field names
var $heading = true; var $heading = true;
# override field names # override field names
var $fields = []; var $fields = [];
# sort entries by this field # sort entries by this field
var $sort_by = null; var $sort_by = null;
var $sort_reverse = false; var $sort_reverse = false;
# delimiter (comma) and enclosure (double quote) # delimiter (comma) and enclosure (double quote)
var $delimiter = ','; var $delimiter = ',';
var $enclosure = '"'; var $enclosure = '"';
# basic SQL-like conditions for row matching # basic SQL-like conditions for row matching
var $conditions = null; var $conditions = null;
# number of rows to ignore from beginning of data # number of rows to ignore from beginning of data
var $offset = null; var $offset = null;
# limits the number of returned rows to specified amount # limits the number of returned rows to specified amount
var $limit = null; var $limit = null;
# number of rows to analyze when attempting to auto-detect delimiter # number of rows to analyze when attempting to auto-detect delimiter
var $auto_depth = 15; var $auto_depth = 15;
# characters to ignore when attempting to auto-detect delimiter # characters to ignore when attempting to auto-detect delimiter
var $auto_non_chars = "a-zA-Z0-9\n\r"; var $auto_non_chars = "a-zA-Z0-9\n\r";
# preferred delimiter characters, only used when all filtering method # preferred delimiter characters, only used when all filtering method
# returns multiple possible delimiters (happens very rarely) # returns multiple possible delimiters (happens very rarely)
var $auto_preferred = ",;\t.:|"; var $auto_preferred = ",;\t.:|";
# character encoding options # character encoding options
var $convert_encoding = false; var $convert_encoding = false;
var $input_encoding = 'ISO-8859-1'; var $input_encoding = 'ISO-8859-1';
var $output_encoding = 'ISO-8859-1'; var $output_encoding = 'ISO-8859-1';
# used by unparse(), save(), and output() functions # used by unparse(), save(), and output() functions
var $linefeed = "\r\n"; var $linefeed = "\r\n";
# only used by output() function # only used by output() function
var $output_delimiter = ','; var $output_delimiter = ',';
var $output_filename = 'data.csv'; var $output_filename = 'data.csv';
/** /**
* Internal variables * Internal variables
*/ */
# current file # current file
var $file; var $file;
# loaded file contents # loaded file contents
var $file_data; var $file_data;
# array of field values in data parsed # array of field values in data parsed
var $titles = []; var $titles = [];
# two dimentional array of CSV data # two dimentional array of CSV data
var $data = []; var $data = [];
/** /**
* Constructor * Constructor
* @param input CSV file or string * @param input CSV file or string
* @return nothing * @return nothing
*/ */
function parseCSV ($input = null, $offset = null, $limit = null, $conditions = null) { function __construct ($input = null, $offset = null, $limit = null, $conditions = null) {
if ( $offset !== null ) $this->offset = $offset; if ( $offset !== null ) $this->offset = $offset;
if ( $limit !== null ) $this->limit = $limit; if ( $limit !== null ) $this->limit = $limit;
if ( count($conditions) > 0 ) $this->conditions = $conditions; if ( count($conditions) > 0 ) $this->conditions = $conditions;
if ( !empty($input) ) $this->parse($input); if ( !empty($input) ) $this->parse($input);
} }
// ============================================== // ==============================================
// ----- [ Main Functions ] --------------------- // ----- [ Main Functions ] ---------------------
// ============================================== // ==============================================
/** /**
* Parse CSV file or string * Parse CSV file or string
* @param input CSV file or string * @param input CSV file or string
@ -184,7 +184,7 @@ class parseCSV {
} }
return true; return true;
} }
/** /**
* Save changes, or new file and/or data * Save changes, or new file and/or data
* @param file file to save to * @param file file to save to
@ -199,7 +199,7 @@ class parseCSV {
$is_php = ( preg_match('/\.php$/i', $file) ) ? true : false ; $is_php = ( preg_match('/\.php$/i', $file) ) ? true : false ;
return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode); return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
} }
/** /**
* Generate CSV based string for output * Generate CSV based string for output
* @param output if true, prints headers and strings to browser * @param output if true, prints headers and strings to browser
@ -220,7 +220,7 @@ class parseCSV {
} }
return $data; return $data;
} }
/** /**
* Convert character encoding * Convert character encoding
* @param input input character encoding, uses default if left blank * @param input input character encoding, uses default if left blank
@ -232,7 +232,7 @@ class parseCSV {
if ( $input !== null ) $this->input_encoding = $input; if ( $input !== null ) $this->input_encoding = $input;
if ( $output !== null ) $this->output_encoding = $output; if ( $output !== null ) $this->output_encoding = $output;
} }
/** /**
* Auto-Detect Delimiter: Find delimiter by analyzing a specific number of * Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
* rows to determine most probable delimiter character * rows to determine most probable delimiter character
@ -244,13 +244,13 @@ class parseCSV {
* @return delimiter character * @return delimiter character
*/ */
function auto ($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) { function auto ($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
if ( $file === null ) $file = $this->file; if ( $file === null ) $file = $this->file;
if ( empty($search_depth) ) $search_depth = $this->auto_depth; if ( empty($search_depth) ) $search_depth = $this->auto_depth;
if ( $enclosure === null ) $enclosure = $this->enclosure; if ( $enclosure === null ) $enclosure = $this->enclosure;
if ( $preferred === null ) $preferred = $this->auto_preferred; if ( $preferred === null ) $preferred = $this->auto_preferred;
if ( empty($this->file_data) ) { if ( empty($this->file_data) ) {
if ( $this->_check_data($file) ) { if ( $this->_check_data($file) ) {
$data = &$this->file_data; $data = &$this->file_data;
@ -258,24 +258,24 @@ class parseCSV {
} else { } else {
$data = &$this->file_data; $data = &$this->file_data;
} }
$chars = []; $chars = [];
$strlen = strlen($data); $strlen = strlen($data);
$enclosed = false; $enclosed = false;
$n = 1; $n = 1;
$to_end = true; $to_end = true;
// walk specific depth finding posssible delimiter characters // walk specific depth finding posssible delimiter characters
for ( $i=0; $i < $strlen; $i++ ) { for ( $i=0; $i < $strlen; $i++ ) {
$ch = $data{$i}; $ch = $data{$i};
$nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ; $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
$pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ; $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
// open and closing quotes // open and closing quotes
if ( $ch == $enclosure && (!$enclosed || $nch != $enclosure) ) { if ( $ch == $enclosure && (!$enclosed || $nch != $enclosure) ) {
$enclosed = ( $enclosed ) ? false : true ; $enclosed = ( $enclosed ) ? false : true ;
// inline quotes // inline quotes
} elseif ( $ch == $enclosure && $enclosed ) { } elseif ( $ch == $enclosure && $enclosed ) {
$i++; $i++;
@ -287,7 +287,7 @@ class parseCSV {
} else { } else {
$n++; $n++;
} }
// count character // count character
} elseif (!$enclosed) { } elseif (!$enclosed) {
if ( !preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch) ) { if ( !preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch) ) {
@ -299,7 +299,7 @@ class parseCSV {
} }
} }
} }
// filtering // filtering
$depth = ( $to_end ) ? $n-1 : $n ; $depth = ( $to_end ) ? $n-1 : $n ;
$filtered = []; $filtered = [];
@ -308,24 +308,24 @@ class parseCSV {
$filtered[$match] = $char; $filtered[$match] = $char;
} }
} }
// capture most probable delimiter // capture most probable delimiter
ksort($filtered); ksort($filtered);
$delimiter = reset($filtered); $delimiter = reset($filtered);
$this->delimiter = $delimiter; $this->delimiter = $delimiter;
// parse data // parse data
if ( $parse ) $this->data = $this->parse_string(); if ( $parse ) $this->data = $this->parse_string();
return $delimiter; return $delimiter;
} }
// ============================================== // ==============================================
// ----- [ Core Functions ] --------------------- // ----- [ Core Functions ] ---------------------
// ============================================== // ==============================================
/** /**
* Read file to string and call parse_string() * Read file to string and call parse_string()
* @param file local CSV file * @param file local CSV file
@ -336,7 +336,7 @@ class parseCSV {
if ( empty($this->file_data) ) $this->load_data($file); if ( empty($this->file_data) ) $this->load_data($file);
return ( !empty($this->file_data) ) ? $this->parse_string() : false ; return ( !empty($this->file_data) ) ? $this->parse_string() : false ;
} }
/** /**
* Parse CSV strings to arrays * Parse CSV strings to arrays
* @param data CSV string * @param data CSV string
@ -348,7 +348,7 @@ class parseCSV {
$data = &$this->file_data; $data = &$this->file_data;
} else return false; } else return false;
} }
$rows = []; $rows = [];
$row = []; $row = [];
$row_count = 0; $row_count = 0;
@ -358,19 +358,19 @@ class parseCSV {
$enclosed = false; $enclosed = false;
$was_enclosed = false; $was_enclosed = false;
$strlen = strlen($data); $strlen = strlen($data);
// walk through each character // walk through each character
for ( $i=0; $i < $strlen; $i++ ) { for ( $i=0; $i < $strlen; $i++ ) {
$ch = $data{$i}; $ch = $data{$i};
$nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ; $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
$pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ; $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
// open and closing quotes // open and closing quotes
if ( $ch == $this->enclosure && (!$enclosed || $nch != $this->enclosure) ) { if ( $ch == $this->enclosure && (!$enclosed || $nch != $this->enclosure) ) {
$enclosed = ( $enclosed ) ? false : true ; $enclosed = ( $enclosed ) ? false : true ;
if ( $enclosed ) $was_enclosed = true; if ( $enclosed ) $was_enclosed = true;
// inline quotes // inline quotes
} elseif ( $ch == $this->enclosure && $enclosed ) { } elseif ( $ch == $this->enclosure && $enclosed ) {
$current .= $ch; $current .= $ch;
$i++; $i++;
@ -382,7 +382,7 @@ class parseCSV {
$row[$key] = $current; $row[$key] = $current;
$current = ''; $current = '';
$col++; $col++;
// end of row // end of row
if ( $ch == "\n" || $ch == "\r" ) { if ( $ch == "\n" || $ch == "\r" ) {
if ( $this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions) ) { if ( $this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions) ) {
@ -406,7 +406,7 @@ class parseCSV {
$i = $strlen; $i = $strlen;
} }
} }
// append character to current field // append character to current field
} else { } else {
$current .= $ch; $current .= $ch;
@ -421,7 +421,7 @@ class parseCSV {
} }
return $rows; return $rows;
} }
/** /**
* Create CSV data from array * Create CSV data from array
* @param data 2D array with data * @param data 2D array with data
@ -436,10 +436,10 @@ class parseCSV {
if ( !is_array($data) || empty($data) ) $data = &$this->data; if ( !is_array($data) || empty($data) ) $data = &$this->data;
if ( !is_array($fields) || empty($fields) ) $fields = &$this->titles; if ( !is_array($fields) || empty($fields) ) $fields = &$this->titles;
if ( $delimiter === null ) $delimiter = $this->delimiter; if ( $delimiter === null ) $delimiter = $this->delimiter;
$string = ( $is_php ) ? "<?php header('Status: 403'); die(' '); ?>".$this->linefeed : '' ; $string = ( $is_php ) ? "<?php header('Status: 403'); die(' '); ?>".$this->linefeed : '' ;
$entry = []; $entry = [];
// create heading // create heading
if ( $this->heading && !$append ) { if ( $this->heading && !$append ) {
foreach( $fields as $key => $value ) { foreach( $fields as $key => $value ) {
@ -448,7 +448,7 @@ class parseCSV {
$string .= implode($delimiter, $entry).$this->linefeed; $string .= implode($delimiter, $entry).$this->linefeed;
$entry = []; $entry = [];
} }
// create data // create data
foreach( $data as $key => $row ) { foreach( $data as $key => $row ) {
foreach( $row as $field => $value ) { foreach( $row as $field => $value ) {
@ -457,10 +457,10 @@ class parseCSV {
$string .= implode($delimiter, $entry).$this->linefeed; $string .= implode($delimiter, $entry).$this->linefeed;
$entry = []; $entry = [];
} }
return $string; return $string;
} }
/** /**
* Load local file or string * Load local file or string
* @param input local CSV file * @param input local CSV file
@ -488,16 +488,16 @@ class parseCSV {
} }
return false; return false;
} }
// ============================================== // ==============================================
// ----- [ Internal Functions ] ----------------- // ----- [ Internal Functions ] -----------------
// ============================================== // ==============================================
/** /**
* Validate a row against specified conditions * Validate a row against specified conditions
* @param row array with values from a row * @param row array with values from a row
* @param conditions specified conditions that the row must match * @param conditions specified conditions that the row must match
* @return true of false * @return true of false
*/ */
function _validate_row_conditions ($row = [], $conditions = null) { function _validate_row_conditions ($row = [], $conditions = null) {
@ -523,11 +523,11 @@ class parseCSV {
} }
return false; return false;
} }
/** /**
* Validate a row against a single condition * Validate a row against a single condition
* @param row array with values from a row * @param row array with values from a row
* @param condition specified condition that the row must match * @param condition specified condition that the row must match
* @return true of false * @return true of false
*/ */
function _validate_row_condition ($row, $condition) { function _validate_row_condition ($row, $condition) {
@ -583,7 +583,7 @@ class parseCSV {
} }
return '1'; return '1';
} }
/** /**
* Validates if the row is within the offset or not if sorting is disabled * Validates if the row is within the offset or not if sorting is disabled
* @param current_row the current row number being processed * @param current_row the current row number being processed
@ -593,7 +593,7 @@ class parseCSV {
if ( $this->sort_by === null && $this->offset !== null && $current_row < $this->offset ) return false; if ( $this->sort_by === null && $this->offset !== null && $current_row < $this->offset ) return false;
return true; return true;
} }
/** /**
* Enclose values if needed * Enclose values if needed
* - only used by unparse() * - only used by unparse()
@ -611,7 +611,7 @@ class parseCSV {
} }
return $value; return $value;
} }
/** /**
* Check file data * Check file data
* @param file local filename * @param file local filename
@ -624,8 +624,8 @@ class parseCSV {
} }
return true; return true;
} }
/** /**
* Check if passed info might be delimiter * Check if passed info might be delimiter
* - only used by find_delimiter() * - only used by find_delimiter()
@ -656,7 +656,7 @@ class parseCSV {
} else return false; } else return false;
} }
} }
/** /**
* Read local file * Read local file
* @param file local filename * @param file local filename
@ -689,7 +689,7 @@ class parseCSV {
} }
return false; return false;
} }
} }
?> ?>