Inserting events that contain non-ASCII characters

2019-02-23 08:11发布

问题:

I'm having trouble inserting events using v3 of the Google Calendar API (PHP).

If a description for an event contains a character such as the pound sign £, the event is created in the calendar but the description is left blank. It seems that this is true of all characters outside of the initial 7-bit character codes (ASCII codes 0-127).

By using the htmlentities function I am able to replace all instances of the pound sign with: £

This is fine if the user is using a web-based version of Google Calendar but mobile apps do not convert this back to the pound sign.

This is quite a big issue as events are often copy/pasted from Microsoft Word which uses non-ascii quotation marks.

Is there a certain method of encoding that will get around this? I'm currently using UTF-8 encoding in the MySQL database and PHP scripts.

I'm using the following code to create the event:

function buildGoogleEvent($title,$description,$start_time,$end_time,$location) {
    // Create an event object and set some basic event information
    $event = new Google_Event();
    $event->setSummary($title);
    $event->setLocation($location);
    $event->setDescription(htmlentities($description, ENT_NOQUOTES, 'utf-8'));

    // Convert the start and end date/times to ATOM format
    $start_time_atom = str_replace(" ", "T", $start_time);
    $end_time_atom = str_replace(" ", "T", $end_time);

    // Add the event start to the event object
    $start = new Google_EventDateTime();
    $start->setDateTime($start_time_atom);
    $start->setTimeZone('Europe/London');
    $event->setStart($start);

    // Add the event end to the event object
    $end = new Google_EventDateTime();
    $end->setDateTime($end_time_atom);
    $end->setTimeZone('Europe/London');
    $event->setEnd($end);

    return $event;
}

And this code inserts the event:

$createdEvent = $service->events->insert($google_calendar_id, $event);

Been sitting on this for quite a while so any help is appreciated! My PHP version is 5.5.4.

回答1:

It turns out there's an easy solution to this. I'd set the HTTP header to use the utf-8 charset but hadn't specifically encoded my description. To add my description to the event I'm now using:

$event->setDescription(utf8_encode($description));