简体   繁体   中英

PHP file download adds extra spaces

I am currently working with jQuery FullCalendar plugin and I just made a function which exports my events into a Google Calendar format. The problem I encounter is that when I download it, I have two extra spaces at the beginning of the file. Unfortunatly, the import fails due to these spaces.

Here's how I create the file and generate the download :

    $ical = "BEGIN:VCALENDAR
            VERSION:2.0";
    foreach($events as $e){
            $ical .= "\nBEGIN:VEVENT
            UID:" . md5(uniqid(mt_rand(), true)) . "@example.test
            DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
            DTSTART: ". $this->formatDate($e['E_dateStart']) ."
            DTEND:". $this->formatDate($e['E_dateEnd']) ."
            SUMMARY:". $e['E_description'] ."
            END:VEVENT";
        }
    $ical .= "\nEND:VCALENDAR";
    $ical = str_replace("\t", "", $ical);
    $ical = str_replace(" ", "", $ical);

    header('Content-type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename=calendar.ics');
    echo "$ical";
    exit;

And then the downloaded file looks like this :

    BEGIN:VCALENDAR
  VERSION:2.0
  BEGIN:VEVENT
  UID:3a24a50a6b9af94c0665c6528f9e38aa@example.test
  DTSTAMP:20150330T083230Z
  DTSTART:20150329T000000Z
  DTEND:20150327T001200Z
  SUMMARY:test
  END:VEVENT
  END:VCALENDAR

I have two spaces just before BEGIN VCALENDAR and I can't figure out where it comes from. I'm guessing it is caused by PHP echo but I'm not sure and I don't know how I could do it differently.

I came with the same problem and my friend I found a quick solution for this.

You have to just add a single line before your code.

ob_clean();

$ical = "BEGIN:VCALENDAR
         VERSION:2.0";

I found out where it came from. If searched into every file I called in my controller and I had extra spaces in some managers after the PHP closing tag.
So if this problem occurs to someone else, just check your managers or whatever you call/initialize in your controller and check the end of the file and delete extra spaces.

trim() is your friend. :) If the space still shows when you echo trim($ical) , you must have trailing spaces somewhere in your file preceding the code above, possibly before your PHP opening tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM