通过CSV导入更新自定义帖子

时间:2021-07-14 作者:agxer

我正在编写一个插件,以便定期上载CSV文件以更新post metas中的数据。问题是,列的顺序有时会随着提供给我的每个CSV文件而改变。我的代码使用列的编号匹配列:

$名称=修剪($csvData[3]);

是否有办法通过列的名称来定位列?(csv的第一行)如:

$名称=修剪($csvData[名字]);

1 个回复
SO网友:Nayan
    <?php
    class CsvReader{
      var $fields;            /** columns names retrieved after parsing */
        var $separator = \';\';    /** separator used to explode each line */
        var $enclosure = \'"\';    /** enclosure used to decorate each field */
    
        var $max_row_size = 4096;    /** maximum row size to be used for decoding */
    
        function parse_file($p_Filepath) {
    
            $file = fopen($p_Filepath, \'r\');
            $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
            $keys_values = explode(\',\',$this->fields[0]);
    
            $content    =   array();
            $keys   =   $this->escape_string($keys_values);
    
            $i  =   1;
            while( ($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false ) {
                if( $row != null ) { // skip empty lines
                    $values =   explode(\',\',$row[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]] =   $new_values[$j];
                            }
                        }
    
                        $content[$i]=   $arr;
                        $i++;
                    }
                }
            }
            fclose($file);
            return $content;
        }
    
        function escape_string($data){
            $result =   array();
            foreach($data as $row){
                $result[]   =   str_replace(\'"\', \'\',$row);
            }
            return $result;
        }
    }

/*Declaration*/

$csv= new CsvReader();
$csvData=$csv->parse_file($uploaded_csv_path);
print_r($csvData);
    ?>