Question

I want to parse text from my database into a CSV-file with PHP. The problem is that nothing is parsed to the file.

function exportToCSV($output)
{
    if(isset($output))
    {
        $fp = fopen("skrivtest/test.csv", "w");
        foreach($output as $out) 
        {
            echo $out . "<br>";
            fputcsv($fp, $out); 
        }
        fclose($fp);
        return true;
    }
    else    
    {
        return false;
    }
}

if($export_csv)
{
    if(!exportToCSV($output = array($row->fornamn . " " . $row->efternamn . " " . $row->personnr . " " . $row->gatuadress . " " . $row->postnr . " " . $row->postadress, '')))
    {
        echo "Can't reach function";
        exit;
    }
}

The output from var_dump($output)

array(2) { [0]=> string(62) "Helene Schultzberg 520622-2902 Fröseke Nygärdet 360 77 FRÖSEKE" [1]=> string(0) "" } Helene Schultzberg xxxx Fröseke Nygärdet 360 77 FRÖSEKE

array(2) { [0]=> string(61) "Dan Johansson 560122-2754 Fibblegård Herråkra 360 73 LENHOVDA" [1]=> string(0) "" } Dan Johansson xxxxx Fibblegård Herråkra 360 73 LENHOVDA

array(2) { [0]=> string(55) "Owe Lindahl 600521-2797 Östraby Kvarn 2 360 73 LENHOVDA" [1]=> string(0) "" } Owe Lindahl xxxx Östraby Kvarn 2 360 73 LENHOVDA

array(2) { [0]=> string(56) "Madelene Runberg 680302-2703 Östervik 14 360 73 LENHOVDA" [1]=> string(0) "" } Madelene Runberg xxxx Östervik 14 360 73 LENHOVDA

array(2) { [0]=> string(48) "Bo Söderberg 420818-0077 Änghult 360 73 LENHOVDA" [1]=> string(0) "" } Bo Söderberg xxxxxx Änghult 360 73 LENHOVDA

Was it helpful?

Solution

Why you are doing it in PHP side when you can do it in SQL side?

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

(the documentation for this is here)

OTHER TIPS

$output = array($row->fornamn . " " . $row->efternamn . " " . $row->personnr . " " . $row->gatuadress . " " . $row->postnr . " " . $row->postadress, ''

should be replaced with

$output = array($row->fornamn, $row->efternamn, $row->personnr, $row->gatuadress, $row->postnr, $row->postadress)

$fp = fopen("filename.csv","w"); $value = array($var1,$var2,$var3); fputcsv($fp,$value,"\t");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top