Search code examples
phparrayscsvfgetcsv

fgetcsv convert array to string with double quote enclosure


I am getting data from a csv as an array using the fgetcsv function. I want to convert the array into a string, so I have used the implode function.

CODE:

if (($handle = fopen("storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $datafinal = implode(",",$data);
        echo $datafinal;
    }
    fclose($handle);
}

I am getting the result string say as Ter Aar, Netherlands,4.7159509,52.164688,,211316. But I would like each entry to be enclosed by double quotes. How can I do that?

Expected result: `"Ter Aar", "Netherlands","4.7159509","52.164688","","211316"

My approach #1 -

I passed the " as enclosure following the documentation but it is not working.

if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
        $datafinal = implode(",",$data);
        echo $datafinal;
    }
    fclose($handle);
}

My approach #2 -

function convert( $str ) {
   return '"'.$str.'"';
}

if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
        //$datafinal = array_map( convert, $data );  
        $datafinal = implode(",",$data);
        echo $datafinal;
        //var_dump($data);
    }
    fclose($handle);
}

This returns a string as "Ter Aar", "Netherlands","4.7159509","52.164688","","""211316".

As you can see the item following the blank data gets three quotes in the beginning.


Solution

  • You can do it as follows

    // PHP 5.3 and later
    echo $datafinal = implode(",",array_filter($data, function($value) { return $value !== ''; })); 
    

    This will help you sure

    Thanks Hope! It will help you