I have a .txt (csv) file which I want to read thru PHP and arrange it in arrays so that I can later insert
or update
it into MySQL, The text
file is like this:
FIELD1;FIELD2;FIELD3;FIELD4
CATEGORY 1(SOME VALUE in PARENTHESIS)
Sub-Category 1
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
Sub-Category 2
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
CATEGORY 2(SOME VALUE in PARENTHESIS)
Sub-Category 1
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
VALUEof1;VALUEof2;VALUEof3;VALUEof4
I have been able to read each line separately beyond that I have gone completely blank and not able to figure out what is to be done, any advice or direction will be appreciated
You can use MYSQL query as below to import the .csv file. Keep in mind that you have to match the columns in the CSV file to those in the table. Also, i will recommend that you to refer the LOAD DATA INFILE.
https://dev.mysql.com/doc/refman/5.7/en/load-data.html
$query = <<<EOF
LOAD DATA LOCAL INFILE '$file'
INTO TABLE users
FIELDS TERMINATED BY ','
LINES TERMINATED BY '
'
IGNORE 1 LINES
(name,mobile,email)
EOF;
Please use this function for parsing the file.Now you will get the data in an array , so you can easily insert to database.
function parse_data( $file, $delimiter) {
// Set locale
$enc = mb_detect_encoding( $file, 'UTF-8, ISO-8859-1', true );
if ( $enc )
setlocale( LC_ALL, 'en_US.' . $enc );
@ini_set( 'auto_detect_line_endings', true );
$parsed_data = array();
$raw_headers = array();
// Put all CSV data into an associative array
if ( ( $handle = fopen( $file, "r" ) ) !== FALSE ) {
$header = fgetcsv( $handle, 0, $delimiter );
if ( $start_pos != 0 )
fseek( $handle, $start_pos );
while ( ( $postdata = fgetcsv( $handle, 0, $delimiter ) ) !== FALSE ) {
$row = array();
foreach ( $header as $key => $heading ) {
if ( $heading == '' )
continue;
// Add the heading to the parsed data
$row[$heading] = ( isset( $postdata[$key] ) ) ? $postdata[$key]: '';
// Raw Headers stores the actual column name in the CSV
$raw_headers[ $heading ] = $heading;
}
$parsed_data[] = $row;
unset( $postdata, $row );
}
fclose( $handle );
}
return array( $parsed_data, $raw_headers );
}