Search code examples
kml

How to add an ampersand in KML?


What is the proper format for including an ampersand in KML? I am using them in the name tag. If I include a regular '&' then it is invalid.

What other characters do I need to properly encode?

I'm using this format:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">

I'm looking for a PHP solution. I'm creating the KML in PHP.


Solution

  • KML is an XML file so simply follow the XML rules to encode special characters. In XML you can encode "&" and other special characters with "predefined entities" that represent the associated special characters or using a CDATA section.

    1. Predefined entities

    The XML specification defines five "predefined entities" representing special characters and requires that all XML processors honor them. Use these special predefined entities names that are substituted with the actual characters it represents when element content is evaluated.

    name  | characters
    ----- | ------
    <     | &lt;
    >     | &gt;
    &     | &amp;
    "     | &quot;
    '     | &apos;
    

    Example:

    <description>
      &lt;a href="http://server.com/link"&gt;A &amp; B&lt;/a&gt;
    </description>
    

    2. CDATA

    Another mechanism to escape markup inside XML elements is CDATA. CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

    Example:

    <description>
      <![CDATA[
        <a href="http://server.com/link">A & B</a>
      ]]>
    </description>