PHP file download adds extra spaces

谁都会走 提交于 2019-12-24 16:58:52

问题


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.


回答1:


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";



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/29341859/php-file-download-adds-extra-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!