PHP CSV string to array

前端 未结 10 1239
攒了一身酷
攒了一身酷 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

    I have used following function to parse csv string to associative array

    public function csvToArray($file) {
        $rows = array();
        $headers = array();
        if (file_exists($file) && is_readable($file)) {
            $handle = fopen($file, 'r');
            while (!feof($handle)) {
                $row = fgetcsv($handle, 10240, ',', '"');
                if (empty($headers))
                    $headers = $row;
                else if (is_array($row)) {
                    array_splice($row, count($headers));
                    $rows[] = array_combine($headers, $row);
                }
            }
            fclose($handle);
        } else {
            throw new Exception($file . ' doesn`t exist or is not readable.');
        }
        return $rows;
    }
    

    if your csv file name is mycsv.csv then you call this function as:

    $dataArray = csvToArray(mycsv.csv);
    

    you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/

    0 讨论(0)
  • 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( '/(?<!")""/', '!!Q!!', $csv_string )
                    )
                ))
            );
            return $FirstLineTitle ? array_splice($arr, 1) : $arr;
        }
    
    0 讨论(0)
  • 2020-11-27 03:38

    Try this, it's working for me:

    $delimiter = ",";
      $enclosure = '"';
      $escape = "\\" ;
      $rows = array_filter(explode(PHP_EOL, $content));
      $header = NULL;
      $data = [];
    
      foreach($rows as $row)
      {
        $row = str_getcsv ($row, $delimiter, $enclosure , $escape);
    
        if(!$header) {
          $header = $row;
        } else {
          $data[] = array_combine($header, $row);
        }
      }
    
    0 讨论(0)
  • 2020-11-27 03:39

    Handy oneliner:

    $csv = array_map('str_getcsv', file('data.csv'));
    
    0 讨论(0)
提交回复
热议问题