Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fputcsv - only one column

I want to save parts (and differently arranged) of my mysql database in a CSV file. For that I wrote this piece of code:

$headerDisplayed = false;
foreach ($arr as &$currName)
{
    $result2 = mysql_query("SELECT * FROM Experiment Where Person='$currName'"); 
    $i = 1;
    while ($row2 = mysql_fetch_array($result2)) 
    {
        $list['Name'] = $currName;
        $list['Studie'] = $row2['Studie']; 
        if(strcmp($row2['Antwort'],$row2['Korrekt']) == 0)
        {
            $list["A $i"] = '0';
        }
        else
        {
            $list["A $i"] = '1';
        }

        $i++;
    }

    if ( !$headerDisplayed ) {
        // Use the keys from $data as the titles
        fputcsv($fp, array_keys($list));
        $headerDisplayed = true;
    }

    fputcsv($fp, $list);
}

fclose($fp);

Unfortunately this does not what I wanted it to do. My plan was that each entry of $list (e.g. $list["A 1"] or $list["A 15"]) has its own column. And then the call of fputcsv should create a new line and again one column for each $list entry. I create new rows with each fputcsv call, just as expected, but the complete $list array is in the first (most left) column.

What do I have to do to solve this issue?

ADDED: I get something like:

[1,0,0,0,1,1,0,0] [] [] [] [] [] [] []

[1,0,1,1,0,1,0,0] [] [] [] [] [] [] []

[0,1,1,1,1,1,0,1] [] [] [] [] [] [] []

but what I want is more like:

[1] [0] [0] [0] [1] [1] [0] [0]

[1] [0] [1] [1] [0] [1] [0] [0]

[0] [1] [1] [1] [1] [1] [0] [1]
like image 231
Matthias Avatar asked Dec 21 '22 18:12

Matthias


2 Answers

This this:

fputcsv($fp, array_values($list));

EDIT:

Use this to get it instantly working with excel:

fputcsv($fp, array_values($list), ';', ' ');

EDIT 2: The default character that is used as the field-separator in excel is set by the locale settings of windows. That means: If you export a csv-file with german locale settings will cause problems with excel in an us-environment... Another thread covered this topic.

like image 58
Ron Avatar answered Dec 27 '22 03:12

Ron


Try this

fputs($fp, implode(array_keys($list), ',')."\n");

fputs($fp, implode(array_values($list), ',')."\n");
like image 37
Justin John Avatar answered Dec 27 '22 02:12

Justin John