PHP CSV string to array

前端 未结 10 1271
攒了一身酷
攒了一身酷 2020-11-27 02:41

I\'m trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Encl         


        
10条回答
  •  死守一世寂寞
    2020-11-27 03:38

    You can convert CSV string to Array with this function.

        function csv2array(
            $csv_string,
            $delimiter = ",",
            $skip_empty_lines = true,
            $trim_fields = true,
            $FirstLineTitle = false
        ) {
            $arr = array_map(
                function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
                    if ($FirstLineTitle && !$FirstLine) {
                        $FirstLine = explode( $delimiter, $result[0] );
                    }
                    $lineResult = array_map(
                        function ( $field ) {
                            return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
                        },
                        $trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
                    );
                    return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
                },
                ($result = preg_split(
                    $skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
                    preg_replace_callback(
                        '/"(.*?)"/s',
                        function ( $field ) {
                            return urlencode( utf8_encode( $field[1] ) );
                        },
                        $enc = preg_replace( '/(?

提交回复
热议问题