Import xml and csv files

I have two tables(course and course_categories). Course is the main table with foreign key course_category_id.

I have these issues:

  1. How do I create an option to either import using xml or csv in the view:course

  2. How do I import xml file and save in the database for both course and course_categories

  3. How do I import csv file and save in the database for both course and course_categories

MODEL: course




    public function attributeLabels()

    {

        return [

            'course_id' => 'Course ID',

            'course_category_id' => 'Course Category',

            'course_code' => 'Course Short Name',

            'course_name' => 'Course Full Name',

            'course_num' => 'Course ID Number',

            'course_summary' => 'Course Summary',

            'course_start_date' => 'Course Start Date',

            'course_format' => 'Course Format',

            'course_format_no' => 'No.of Sections',

            'course_file_path' => 'Course File',

            'show_grade' => 'Show Grade',

        ];

    }




MODEL: course_categories




    public function attributeLabels()

    {

        return [

            'course_category_id' => Yii::t('app', 'ID'),

            'course_category_name' => Yii::t('app', 'Category Name'),

            'course_category_desc' => Yii::t('app', 'Description'),

            'course_category_parent_id' => Yii::t('app', 'Category Parent'),


        ];

    }




Please help me out.

Are you talking about having users upload the xml or csv files to the site and having the files read and data inserted into the database? You would need a form with file upload capability. In the form model you could restrict file types to .xml or .csv, and based on the extension your controller action would use string or simpleXML methods to read the information and save the data. These methods would have to check for missing fields, and valid foreign keys, etc.

I am not an expert and I would be nervous about this type of user activity. I would have authorized users adding data with the create methods based on gii generated CRUD with the model’s rules applied. This limits entry to one row at a time but is more secure.

Yes. Thats what I need. Can you help me with sample

Sorry for the long delay, I had a flu that put me on my back for a while.

There are different ways to accomplish what you’re looking to do. You can have a separate file upload form model & form view, using SiteController to process the files, or you could have ‘file’ as one of your attributes of the model(s) you’re working with. The Yii2 documentation on file upload will help you if you just want to make a simple file upload model which would probably be easier.

Look up SimpleXML for parsing the XML files. The CSV files would require php string manipulation.

1 Like