Using & Formatting HTML Text in Flash

I import XML into my Flash projects a lot. From time to time, the XML will contain special characters that can’t be rendered by Flash.  Or maybe it will contain text that should act as a hyperlink, or be bold or italic.  Whatever the case may be, there are a few key steps to successfully importing and displaying these special characters and HTML styles.

First, we need to set up the XML file.  In the text editor of your choice, you can begin setting it up by entering the following code:

<?xml version=”1.0″ encoding=”utf-8″?>
<site>
  <theItem></theItem>
</site>

In the code above, we simply set up the main tag, named site, and put another tag named theItem inside of it. (I’m not going to get into explaining best practices for setting up XML files here. That’s a topic for another post.)  Inside the theItem tag, we can put our text. I’ll start by putting one sentence, contained inside of a <p> tag, with <b>, <i>, and <a> HTML tags.

<theItem><p>This is an example of XML text with <b>bold</b> and <i>italic</i> words, as well as <a href=”#”>hyperlinks</a>.</p></theItem>

Save your XML file as “text.xml”.

Now that we have the XML built, let’s move over to Adobe Flash and import the XML.  With Adobe Flash open, create a new ActionScript 3.0 file, and make a new dynamic text field and name it “text_txt”.  Set the color, font, and size to your own liking.  Then, create a new layer, named Actions, and lock it.  (I always name my ActionScript layer “Actions”, lock it, and put it as the top layer.  It’s a good practice to get into if you don’t already.)  Save your Flash file in the same directory location as the XML file.

Now, in your Actions panel, type the following code:

var theXML:XML;
var xmlData:Array = new Array();
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, processXML);
loader.load(new URLRequest(“test.xml”));
function processXML(e:Event){
  theXML = new XML(e.target.data);
  var xmlLength:Number = theXML.theItem.length();
  for (var i=0; i<xmlLength; i++){
    xmlData[i] = theXML.theItem[i];
  }
  text_txt.text = xmlData[0];
  text_txt.multiline = true;
  text_txt.wordWrap = true;
  text_txt.height = text_txt.textHeight + 6;
}

Here’s a quick rundown of what this code does:
– Define a new XML object named theXML
– Create a new Array named xmlData
– Create a new URLLoader named loader.  This loader then gets an event listener that will fire the function processXML when loading is complete.  To load the XML file, we load a new URLRequest to the path of our XML file (which should be in the same directory as your Flash file.)
– The processXML function then creates our XML object, filling it with the data from the loader.
– Create a number variable containing the length of the XML. This is essential for what’s coming next.
– Run a for loop starting at 0 and going through the length of the XML object.  This loop populates our Array, xmlData, with each theItem tag from the XML.
– Fill the text field with the text from the first spot in the array (our only tag in this example).
– Set multiline and wordWrap to true so the text won’t be limited to one line.
– Set the text field height so it includes all of the text, plus a few extra pixels of buffer at the bottom.

Save your Flash file and test your movie.  You’ll see something very similar to the image below, which isn’t very appealing yet.

Initial Import of XML

Close the test movie and return to your Actions panel.

In the Actions panel, we’re going to change the line of code that sets the text in our text field to the array data.  Instead of using text_txt.text, we’re going to use text_txt.htmlText (see below).  By setting the text field to htmlText, we enable the ability to accept HTML tags and display the results appropriately.

text_txt.htmlText = xmlData[0];

Save your Flash file and re-test your movie.  You’ll notice the results are much nicer, but the lines break up each time there is an HTML tag, as in the image below.  The good news is that the bold and italic tags display the text correctly, and the hyperlink does work.  But there’s really no way to tell the user that the hyperlink is actually a hyperlink.

Flash Export - Text Unstyled

Close the test movie and return to your Actions panel once again.

To style our HTML text, we’re going to need to create a style sheet object and attach it to our text field.  To do this, we can use the following code, placed above our processXML function:

var textStyles:StyleSheet = new StyleSheet();
textStyles.setStyle(“a:link”, {color:‘#01628b’, textDecoration:‘underline’});
textStyles.setStyle(“a:hover”, {color:‘#d68402′, textDecoration:‘underline’});
text_txt.styleSheet = textStyles;

Here, we create a new StyleSheet object, and set styles for <a> tags, based on the correct syntax that Flash uses.  In this example, we assigned a color and underline to our link, and to its hover state.  (For more info on StyleSheets, consult the Flash documentation on StyleSheets.

Lastly, we set the styleSheet attribute on our text field to our StyleSheet object.

Save your Flash file and re-test your movie again.  Our lines are still broke, but our hyperlink now looks like a hyperlink.  We’re getting closer.

Flash Export - Text Styled

Close the test movie, and return to your XML file.

Here, we will get to the key to successfully displaying the HTML content correctly, and on one line:  The CDATA tag.

In order to display HTML content and special characters successfully, we need to put a CDATA tag into our theItem tag.  The syntax of the CDATA tag starts with <![CDATA[ and ends with ]]>.  It wraps around the outside of the theItem content, like this:

<theItem><![CDATA[<p>This is an example of XML text with <b>bold</b> and <i>italic</i> words, as well as <a href="#">hyperlinks</a>.</p>]]></theItem>

Save the XML file, and return to Flash.  Once in Flash, re-rest your movie.  You’ll notice that the text now flows correctly, and is styled according to our HTML tags and style sheet data!

Flash Export - CDATA #1

Ah, sweet success!  We did it!  But the fun doesn’t stop there.  Inside of the CDATA tag, we not only have the ability to successfully show HTML tags, but also special characters.  Let’s put some special characters into our XML tag and see what happens.

To use special characters, we will need to know the respective HTML Entity Number, which can be found at the W3 Schools website here: HTML Symbol Entity Reference.

Now that we have a reference for finding special character entity numbers, we’ll put in another sentence containing a handful of them to see how they look.  In your XML file, add another sentence to the theItem tag, like the one I’ve included below:

<![CDATA[<p>This is an example of XML text with <b>bold</b> and <i>italic</i> words, as well as <a href="#">hyperlinks</a>. It also contains special characters, like Æ, &, ©, ®, and ».</p>]]>

Save the XML file, return to Flash, and re-test your movie.  Notice that the special characters show up correctly, and in line with everything else without those annoying line breaks!

Now, I will say this:  CDATA tags aren’t needed to merely display HTML tags and special characters within Flash. Flash has done a good job with the htmlText attribute, but we still need to set up the XML file with CDATA tags to make the content flow properly without the line breaks.

Here’s a look at our final code for this test:

<!-- XML -->
<?xml version=”1.0″ encoding=”utf-8″?>
<site>
  <theItem>
    <![<p>This is an example of XML text with <b>bold</b> and <i>italic</i> words, as well as <a href="#">hyperlinks</a>. It also contains special characters, like Æ, &, ©, ®, and ».</p>]]>
  </theItem>
</site>

/* ActionScript */
var theXML:XML;
var xmlData:Array = new Array();
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, processXML);
loader.load(new URLRequest(“test.xml”));
var textStyles:StyleSheet = new StyleSheet();
textStyles.setStyle(“a:link”, {color:‘#01628b’, textDecoration:‘underline’});
textStyles.setStyle(“a:hover”, {color:‘#d68402′, textDecoration:‘underline’});
text_txt.styleSheet = textStyles;
function processXML(e:Event){
  theXML = new XML(e.target.data);
  var xmlLength:Number = theXML.theItem.length();
  for (var i=0; i<xmlLength; i++){
    xmlData[i] = theXML.theItem[i];
  }
  text_txt.htmlText = xmlData[0];
  text_txt.multiline = true;
  text_txt.wordWrap = true;
  text_txt.height = text_txt.textHeight + 6;
}

If you want the source files, you can download them here.
Download Source Files »

I hope that this sheds some light on the topic of getting HTML text to correctly display and flow inside of your Flash application.  Until next time, happy coding!

4 Responses to this post:

  • Gary Britten says:

    Hi i was wondering if you could tell me how to restrict the text so it does not expand the text field and allows the scroll bar to work to view the extra text

  • anthony says:

    If you want to use a scrollbar, I’d suggest using the TextArea component in Flash. This component does the work of formatting the text as HTML text, and has built in scrollbar logic to tell when it needs to show/hide based on length.

    With that said, you can do a custom scrollbar if you don’t like the prefab Flash component, but that’ll be a tutorial for another post, as it would take up more space than this comment should contain.

    (In short, make a movie clip. Inside the movie clip, make a text field with a mask on the layer above it. If the text field is taller than the mask, include logic to show and size a scrollbar. Additionally, you’d need to have logic attached to up/down arrows, and a startDrag function on the scrollbar that would position the text field based on its position. Also, if the text field is shorter or equal to the height of the mask, you’d include logic to hide the scrollbar.)

  • I’m having an error I’ve seen posted in other forums but with no good solution.

    I’m reading text html formated as explained here. The problem I have is, if I use the “Use device fonts” options, everything works just fine.
    If I use any other anti-alias(Bitmap Text, for reading, for animation or custom) the and tags doesn’t work. I embedded all the fonts, and even so…
    Any ideas?

  • anthony says:

    Alex,

    I have had the same issue. In my experience, in order to embed fonts and use anti-aliasing options, you need to set a TextFormat to your text field to embed non-standard fonts. The problem I’ve encountered is that you can either have a stylesheet OR a text format attached to your text field, but not both, unfortunately. So if you need HTML supported tags, you’ll be stuck with device fonts.

    Unless I’m missing some way to use both, it’s just an issue we’ll have to deal with until a way is found to use both.

Leave a Comment