Customer Portal

Get Involved. Join the Conversation.

Topic

    Janusz Jasinski
    What is the best way to read a CSV file in OSvC
    Topic posted September 15, 2019 by Janusz JasinskiBronze Crown: 15,000+ Points 
    17 Views, 3 Comments
    Title:
    What is the best way to read a CSV file in OSvC
    Content:

    Hi,

    I'm currently using the below to read a CSV file into an array but I was wondering if there was a trick I was missing in OSvC / RNCPHP?

    private function csvToArray($filename) {
    RNCPHP\ConnectAPI::getCurrentContext()->ApplicationContext = "Putting a CSV file into an array";
    try{
    // Declare variables
    $data = array();
    $filename = HTMLROOT . "/euf/assets/csv/".$filename;
     
    // Process CSV
    if (($handle = fopen($filename, "r")) !== FALSE) {
    while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $data[] = $line;
    }
    }
    }
    catch ( \Exception $err ){
    echo "<br><b>Exception</b>: line ".__LINE__.": ".$err->getMessage()."</br>";
    }
     
    return $data;
    }
    Thanks,
     
    JJ

    Comment

     

    • Sristy Arya
      Hi Janusz, Pls share the error you are encountering while uploading a CSV. Thanks Sristy
      • Sristy Arya

        Hi Janusz,

        PFB the sample code to read csv.

        <?php
        if(isset($_FILES["file1"])){
        $lines = file($_FILES["file1"]["tmp_name"], FILE_IGNORE_NEW_LINES);
        $i=0;
        foreach ($lines as $key => $value){
        if($i==0){
        $headarr[$key] = str_getcsv($value);
        $i++;
        }
        else{
        $rowdata[$key] = str_getcsv($value);
        }
        }
        $cnt=1;
        if(count($rowdata)>0){
        //Rowdata contains all the data of the csv sheet as an array
        for($i=2; $i <= count($rowdata);$i++){
        try{

        $column1=ucfirst(strtolower(trim($rowdata[$i][0])));
        $column2 = strtolower(trim($rowdata[$i][1]));
        $column3 = strtolower(trim($rowdata[$i][2]));

        //fetch data using indexes & play around
        }
        catch(Exception $e){
        echo "<br>Error: ".$e->getMessage()." | Line: ".$e->getLine()."<br>";
        continue;
        }
        }
        }
        }

        ?>

        Thanks

        Sristy