0

I am trying to export the data from table on SQL server database to the CSV file. Data is formatted correctly and placed in each separate cells on the file. But the header is not formatted properly and is printed all on to one cell as a continuous stream.

Say you have a,b,c,d as headers : Header is printed as abcd on to the first cell and is not spitting out on to individual cells. how do we separate them out ?

Here is the code :

$flag = false;
if ($query) {
while( $data = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {


        foreach($data AS $key => $value){
                     if(!$flag) {

      // display field/column names as first row
                        $out .= implode("\t", array_keys($data)) . "\n";
                        //$out .= '"'.$head.'",';
                        $flag = true;
            }

        //If the character " exists, then escape it, otherwise the csv file will be invalid.
        $pos = strpos($value, '"');
        if ($pos !== false) {
            $value = str_replace('"', '\"', $value);
        }
        $out .= '"'.$value.'",';
    }
    $out .= "\n";

}
1

1 Answer 1

1
$out .= implode("\t", array_keys($data)) . "\n";

Is creating a tab separated line, but elsewhere you are using comma separated.

Probably you want to use comma's here as well:

$out .= implode(",", array_keys($data)) . "\n";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.