如何使用PHP将文本文件(CSV)解析为MySQL
我有一个.txt(csv)文件,我想通过PHP读取该文件,并将其排列成数组,以便以后可以如何使用PHP将文本文件(CSV)解析为MySQL,php,mysql,csv,parsing,Php,Mysql,Csv,Parsing,我有一个.txt(csv)文件,我想通过PHP读取该文件,并将其排列成数组,以便以后可以插入或更新到MySQL中,文本文件如下: FIELD1;FIELD2;FIELD3;FIELD4 CATEGORY 1(SOME VALUE in PARENTHESIS) Sub-Category 1 VALUEof1;VALUEof2;VALUEof3;VALUEof4 VALUEof1;VALUEof2;VALUEof3;VALUEof4 VALUEof1;VALUEof2;VALUEof3;VALU
插入
或更新
到MySQL中,文本
文件如下:
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
我已经能够分别阅读每一行了,除了我已经完全空白,无法理解要做什么,任何建议或指导都将不胜感激您可以使用MYSQL查询,如下所示导入.csv文件。 请记住,您必须将CSV文件中的列与表中的列相匹配。 此外,我建议您参考加载数据填充
$query=请使用此函数解析文件。现在您将获得数组中的数据,以便轻松插入数据库
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 );
}
fegtcsv($csv_file)
read this该对象将使用PHP脚本,以便每次自动解析该文件
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 );
}