Search code examples
phpfputcsv

Unwanted new line string / fputcsv


So I am trying to use fputcsv, and it works, almost like it is intented. I have this weird problem, that I can not seem to solve, and I do not find any good documentation or even people who have this problem.

When there is a string that is being put in the csv, it goes well most of the time, but sometime it starts a new line in the middle of the string for no reason, when I go into the MySQL DB it does not show any stuff like \n, of even a weird character.

It just starts a new line for no reason, what I see sometimes is that there is a "long" word written like this: "today is saturday.tomorrow is sunday" and then it starts a new line after tomorrow, there is no space between the period and next word, but this does not seem a good reason to start a new line?

When I print out the array, it also has the same line ending at that spot... Anyone have any idea what it could be?

My apologies if this does not make any sense...

EDIT: added code and examples

public function actionExportCSV()
{
    $model = Vicreg::model()->findAllByAttributes(array('event_id' => $_GET['eventid']));
    if($model){
        $output = fopen("php://output",'w') or die("Can't open php://output");
        header("Content-Type:application/csv"); 
        header("Content-Disposition:attachment;filename=verzorgingen.csv"); 
        fputcsv($output, array('id','event_id','name','firstname','dob','sex','urgency','pathology','pathology_other','treatment','treatment_other','medication','medication_other','material_other','material','docs','hour_in','hour_out','station_id','nurses_id','transport_id','hospital_id','ambulance_id','closed'));
        foreach($model as $vicreg) {
            $array = array();
            //if($vicreg->id == "83") { print_r($vicreg); exit(0); }
            foreach($vicreg->attributes as $key => $attribute) {
                $attribute = str_replace('  ', '', $attribute);
                $array[$key] = trim(stripslashes($attribute));
            }
            fputcsv($output, $array, ',' ,'"');
        }

        fclose($output) or die("Can't close php://output");
    } else {
        throw new CHttpException(422, 'Geen evenement opgegeven');
    }
}

Example

83,4,Name,Firstname,1970-01-01,1,3,4,"normal string",1,"dagelijks 2X te verzorgen. brandwonden 3 dagen geleden opgelopen door knalpot van brommer.
voornamelijk 2de graads brandwonden + open wonde",,,,,,"date","date",5,,1,,,1

After "brommer." there is a new line...


Solution

  • OK so I finally found a solution, I've been looking since 2 days ago. It appears that there is some hidden character, because when I make PHP use the function preg_replace and put in the condition "\n-\x0B-\r" the problem is solved.

    Thought I'd share it, if someone happens to have this issue in the future.