8

I want to post csv file on my controller using API.I'm using Codeigniter REST Library by phil sturgeon. How to implement on the client side the importing of CSV to my REST Server.I just want to ask because I can't find any documentation about it.

program taylor
  • 119
  • 1
  • 2
  • 8
  • You are not enough clear with the question. Codeigniter REST is almost same as normal Codeigniter but the difference is just calling the method and response. In normal codeigniter we calls `controller/function` where in REST it must be `resource/{resource_id}/child_resource/{child_resource_id}`. i don't thing there will be any problem for sending the headers as `.xls` file – KuKu Jul 05 '12 at 05:12
  • clealy and in simple words tell us what you want – Muhammad Raheel Jul 05 '12 at 05:58
  • @raheelshan I want to post csv file on my controller using client side API by jquery.post and extract the csv file data and import to mysql. – program taylor Jul 05 '12 at 06:43

1 Answers1

31

Here is an easy way to do this. I don't know what people do but i use this

This is my csv reader library, Save this in libraries folder as csvreader.php.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

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;
    }   
}
?>

And controller method

function readExcel()
{
        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file('Test.csv');//path to csv file

        $data['csvData'] =  $result;
        $this->load->view('view_csv', $data);  
}

And this is view

<table cellpadding="0" cellspacing="0" width="100%">
    <tr>
            <td width = "10%">ID</td>
            <td width = "20%">NAME</td>
            <td width = "20%">SHORT DESCRIPTION</td>
            <td width = "30%">LONG DESCRIPTION</td>
            <td width = "10%">STATUS</td>
            <td width = "10%">PARENTID</td>
    </tr>

            <?php foreach($csvData as $field){?>
                <tr>
                    <td><?php echo $field['id']?></td>
                    <td><?php echo $field['name']?></td>
                    <td><?php echo $field['shortdesc']?></td>
                    <td><?php echo $field['longdesc']?></td>
                    <td><?php echo $field['status']?></td>
                    <td><?php echo $field['parentid']?></td>
                </tr>
            <?php }?>
</table>

Note : This will only read a file which exists on server. If the file is needed to be uploaded use File Upload Class to upload file and save it to some location on your server then give the path of located file in parse_file method. And everything will work fine.

Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
  • Thanks I'll give it a try I just need the data to extract and pass it to the model. – program taylor Jul 05 '12 at 07:30
  • you can pass the returned array to model – Muhammad Raheel Jul 05 '12 at 07:50
  • how if my csv fields without $enclosure '"'? it return error if i put $enclosure = ''; – Chris Suen Aug 29 '13 at 03:40
  • 1
    @ChrisSuen can you post an example so i can test – Muhammad Raheel Aug 29 '13 at 06:24
  • @raheelshan how should be the csv file to be able to use this exact same view you use in this example? I used this exact same example but I still couldn't display the data of a CSV file I prepared here. :( (it's been a while I don't code in php and I'm trying to get back to it again) – sergioviniciuss Nov 06 '13 at 23:05
  • 1
    Well @Periback you are supposed to create view yourself according to the sequence of fields in csv. If you need different sequence you must rearrange the array. And the above sample code works fine. You might be making mistake somewhere. Can you tell what problem you are facing in detail? – Muhammad Raheel Nov 07 '13 at 06:34
  • sure, I can @raheelshan. I'm trying to read 5 txt files sequentially and they're like csv files, but the separator is semicolon and they have different number of columns. I'm using your approach to read the file and it's working good to do this, but I'm still a bit confused with the array structure, since there's been a while I dont code in PHP. – sergioviniciuss Nov 07 '13 at 22:58
  • @raheelshan, I did it! now I'm just trying to figure out a way to print the data.. – sergioviniciuss Nov 08 '13 at 00:56
  • try this.. perfect '' http://www.sourcecodester.com/download-code?nid=6477&title=How+to+Import+CSV+Data+in+Codeigniter&uri=%2Fphp%2F6477%2Fhow-import-csv-data-codeigniter.html'' – KBK Jul 07 '16 at 01:50
  • Nice, This answer will help me but i want to know in which table i need to import CSV file? I need a code to import CSV file in table. – Vishal Panara Jul 27 '16 at 05:55
  • its up to your own requirements. You will have a collection on which you can loop through and run insert query in database – Muhammad Raheel Jul 28 '16 at 13:33