Search code examples
phpjsonajaxcsvractivejs

Parse CSV file to JSON after uploading using temporary copy


I'm almost finishing building a functionality for parsing CSV files to JSON and just need help in piecing it together. The way it works is that files will be uploaded using AJAX/Jquery. Once the files has been uploaded and sent the PHP to parse the CSV file to JSON will then execute.

After parsing, the converted file will be push or sent to the API as a JSON object. Here is the code that I have been working. For the uploading i'm using this plugin AJAX/JQuery File Uploader

This functionality is also built on using RactiveJS

AJAX/Jquery File Uploader

This is the section where I'm currently uploading or placing the file. URL is pointed at the upload.php.

<div id="fileuploader">Upload</div>

<script>
$(document).ready(function() {
    $("#fileuploader").uploadFile({
        url: 'upload.php',
    });
})
</script>

Uploads.php

Is there a way to GET the temporary copy of the uploaded file and parse using the PHP code I have built below to convert the CSV to JSON

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error' . $_FILES['file']['error'] . '<br/>';
    }

    else {

        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

    }


?>

PHP (CSV to JSON)

Right now be the file is being declared manually.

<?php
    $json_data = csvToJson('lms.csv');
?>  

<?php 


    function csvToJson($fname) {
        if (!($fp = fopen($fname, 'r') )) {
            die("Can't open file");
        }

        else {
            ('Upload File');
        }

        $key = fgetcsv($fp, "1024", ",");

        $json = array();
            while ($row = fgetcsv($fp, "1024", ",")) {
                $json[] = array_combine($key, $row);
        }

        fclose($fp);

        foreach ( $json as $k=>$v ) {

            $json[$k]['accountName']           =     $json[$k]['ACCOUNT NAME']; 
            $json[$k]['dateRequested']         =     $json[$k]['DATE']; 


            unset($json[$k]['ACCOUNT NAME']);
            unset($json[$k]['DATE']);

        }

        return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

    }

 ?>

<?php // $target_file = fopen($_FILES["fileToUpload"]["tmp_name"], 'r'); ?>

Send Converted to API (Ractive/AJAX/JS)

As you can see the sending part is triggered by an on-click event (app.on)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/0.9.0-build-48/ractive.js"></script>



<script type="text/javascript">

var app = new Ractive({
    el       : '#container',
    template : '#template',
});


    var proxy       = 'http://192.168.1.126/lms-dev-noel/proxy.php';
    var endpoint    = 'account/leads/';
    var rt          = 'POST';
    var url         = proxy+'?endpoint='+endpoint+'&rt='+rt;

    var lms_json    = <?php echo json_encode($json_data); ?>;
    var jobjects    = JSON.parse(lms_json);


    for ( i = 0; i < jobjects.length; i++ ) {
        var data = jobjects[i];


        console.log(data);

        $.ajax({
              type     : 'POST',
              url      : url,
              data     : data,
              dataType : 'json',
              success  : function() {

              },
              error    : function(error) {
                  console.log('Error')
              }

        });

    }



</script>

Warning and Notices enter image description here


Solution

  • Well, it depends a bit on where that csvToJson function is located in your code. If it's within uploads.php, or in a separate file that you can include in uploads.php, then you can just do:

    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    
    $json_data = csvToJson('uploads/' . $_FILES['file']['name']);
    echo $json_data;
    

    Then in the script, change

    var lms_json    = <?php echo json_encode($json_data); ?>;
    

    to

    var lms_json;
    

    and move it to the top of your javascript.

    It seems like you are trying to assign the variable before the API call has been made. Instead you need to capture the data from the the response of the uploadFile call (as per these docs: http://hayageek.com/docs/jquery-upload-file.php):

    $("#fileuploader").uploadFile({
        url: 'upload.php',
        onSuccess:function(files,data,xhr,pd)
        {
          //data: response from server
          lms_json = data;
        }
    });