Search code examples
phpstringcsvfgetcsv

Convert comma separated string into two strings after CSV upload [PHP]


I have a script that uploads a csv and assign values to a string separated by comma

$has_title_row = true;
if( $_POST['upload_file'] == 1 ) {
    if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
        $filename = basename($_FILES['csvfile']['name']);

        if(substr($filename, -3) == 'csv'){
            $tmpfile = $_FILES['csvfile']['tmp_name'];
            if (($fh = fopen($tmpfile, "r")) !== FALSE) {
                $i = 0;
                while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) {
                    if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
                        $i++;
                        continue;
                    }
                    //$data = print_r($items);
                    $i++;

                        $num = count($items);

                        $row++;
                        $str = '';
                        for ($c=0; $c < $num; $c++) {
                            //echo $items[$c] . ", ";
                            $str .= $items[$c] . ", ";
                        }
                } 
            }
        }
        else{
            die('Invalid file format uploaded. Please upload CSV.');
        }
    }
    else{
        die('Please upload a CSV file.');
    }
}

In the csv that I am uploading, I have 2 columns City and Country

enter image description here

I am also removing the first row with the title. So in the $str I have something like

$str = "Munich, Germany, Berlin, Germany, London, UK, Paris, France, Vienna, Austria, Milano, Italy, Rome, Italy";

The result I am aiming for is

$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";

How would I separate the $str into countries and cities, or maybe it should be done in the upload scripts where I am looping trough the results?


Solution

  • You can iterate the array, Demo

    $str = "Munich, Germany, Berlin, Germany, London, UK, Paris, France, Vienna, Austria, Milano, Italy, Rome, Italy";
    $array = explode(",",$str);
    foreach($array as $k => $value){
        if($k % 2){
            $country_list[] = $value;
        }else{
            $city_list[] = $value;
        }
    }
    $city = join(",",$city_list);
    $country = join(",",$country_list);