lokomotivan
10/17/2017 - 12:47 PM

Processwire CSV Import/Export

Processwire CSV Import/Export

<form class="uk-form-horizontal" action="./" method="post" enctype="multipart/form-data">
    <div class="uk-modal-body">
        <label class="uk-form-label"><i class="fa fa-file-text-o"></i> CSV File</label>
        <div class="uk-form-controls">
            <div uk-form-custom="target: true">
                <input class="uk-wifth-1-1" type="file" name="csv" accept="csv" />
                <input class="uk-input" type="text" placeholder="Select CSV File" disabled>
            </div>
        </div>
    </div>
    <div class="uk-modal-footer">
        <button class="uk-modal-close uk-button uk-button-default" type="button"><i class="fa fa-close"></i> 
            Cancel
        </button>
        <button class="uk-button uk-button-primary" type="submit" name="import" value="Import">
            <i class="fa fa-cloud-upload"></i> Import
        </button>
    </div>
</form>
<?php
/**
 *   CSV Import
 *
 *  @author Ivan Milincic <lokomotivan@gmail.com>
 *  @copyright 2017 Ivan Milincic
 *
*/

if($input->post->import) {

    // set uplaod path
    $upload_path = $config->paths->assets."files/";
    // WireUpload
    $f = new WireUpload('csv');
    $f->setMaxFiles(1);
    $f->setOverwrite(true);
    $f->setDestinationPath($upload_path);
    $f->setValidExtensions(array('csv'));

    // if there is no uplaod path trow error
    if(!is_dir($upload_path)) {
        if(!wireMkdir($upload_path)) throw new WireException("No upload path!");
    }

    // execute upload
    $files = $f->execute();
    // csv file
    $csv_file  = $upload_path.$files[0];

    try {

        // convert csv file to array
        $csv_array = array_map('str_getcsv', file($csv_file));

        foreach($csv_array as $csv_item) {

            // array vars
            $title          = $sanitizer->text($csv_item[0]);
            $text           = $sanitizer->text($csv_item[1]);
            $image          = $sanitizer->text($csv_item[2]);

            // create page
            if($title && $title != '') {

                $p = new Page();
                $p->template        = 'TEMPLATE_NAME';
                $p->parent          = $pages->get("template=PARENT_TEMPLATE_NAME");
                $p->title           = 'TITLE';
                $p->text            = 'TEXT';
                $p->save();
                if($image && $image != '') {
                    $p->img->add($image);
                    $p->save();
                }

            }

        }

        // set sesion vars
        $_SESSION['status'] = "success";
        $_SESSION['note'] = "Import Complete!";
        // redirect
        header("Location: some_url_here");
        exit();

    }catch(Exception $e) {
        $note_status = 'danger';
        $note = $e->getMessage();
        echo ukNotification("top-center", "$note_status", "$note", "5000");
    }

}

// echo notification after import
if(isset($_SESSION['note'])) {
    echo ukNotification("top-center", "{$_SESSION['note_status']}", "{$_SESSION['note']}", "3000");
    unset($_SESSION['note_status']);
    unset($_SESSION['note']);
}
<?php
/**
 *  Export CSV
 *
 *  @author Ivan Milincic <lokomotivan@gmail.com>
 *  @copyright 2017 Ivan Milincic
 *
*/

if($input->post->export_csv) {

    // get all user items
    $pages_to_export = $pages->find("YOUR_SELECTOR_HERE");

    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=YOUR_FILE_NAME.csv');

    // Convert pw page to regular array
    $array = $pages_to_export->explode(function($item){
        return array(
            'title' => $item->title,
            'category' => $item->category,
            'text' => $item->text,
            'img' => $item->img
        );
    });
    
    /**
     *  Create CSV file with $array
     *  Open file in "w" write mode amd put each item from $array above
     */
    $fp = fopen('php://output', 'w');
    foreach($array as $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);
    exit();

}

?>