PHP: Read and convert CSV data to array

PHP Programing

This php class to read the CSV file. It helps to import a CSV file and convert CSV data into an associative array, it can read CSV files containing Japanese. This class treats the first row of a CSV file as a column header row.

class CSVReader {

    // Columns names after parsing
    private $fields;
    // Separator used to explode each line
    private $separator = ';';
    // Enclosure used to decorate each field
    private $enclosure = '"';
    // Maximum row size to be used for decoding
    private $max_row_size = 10000;

    /**
     * Parse a CSV file and returns as an array.
     *
     * @access    public
     * @param    filepath    string    Location of the CSV file
     *
     * @return mixed|boolean
     */
    function parse_csv($filepath) {

        // If file doesn't exist, return false
        if (!file_exists($filepath)) {
            return FALSE;
        }

        setlocale(LC_ALL, 'ja_JP.UTF-8');
        $data = file_get_contents($filepath);
        $data = mb_convert_encoding($data, 'UTF-8', 'sjis-win');

        $temp = tmpfile();
        $csv = array();

        fwrite($temp, $data);
        rewind($temp);
        $i = 0;
        
        // Get Fields and values
        $this->fields = fgetcsv($temp, $this->max_row_size, $this->separator, $this->enclosure);
        $keys_values = explode(',', $this->fields[0]);
        $keys = $this->escape_string($keys_values);
        
        while (($data = fgetcsv($temp, $this->max_row_size, $this->separator, $this->enclosure)) !== FALSE) {
            if($data != NULL){
                $values = explode(',', $data[0]);
                if(count($keys) == count($values)){
                    $arr = array();
                    $new_values = array();
                    $new_values = $this->escape_string($values);
                    for($j = 0;$j < count($keys);$j++){
                        if($keys[$j] != ""){
                            $arr[$keys[$j]] = htmlentities($new_values[$j]);
                        }
                    }
                    $csv[$i] = $arr;
                    $i++;
                }
            }
        }

        // Close opened CSV file
        fclose($temp);

        return $csv;
    }

    function escape_string($data) {
        $result = array();
        foreach ($data as $row) {
            $result[] = str_replace('"', '', $row);
        }
        return $result;
    }

}