Loading and Saving XML

This is a demo I created to demonstrate how to load and save data to an XML file. In the demo below you can add and remove balls as well as change their color. When you are finished you can click on “save” which saves your work into an XML file.

<?xml version="1.0" encoding="UTF-8"?>
<balllist>
<ball>

<id>0</id>
<x>80</x>
<y>50</y>
<c>0xFF0000</c>
<m>50</m>
</ball>
<ball>

<id>1</id>
<x>330</x>
<y>150</y>
<c>0x00FF00</c>
<m>100</m>
</ball>
<ball>

<id>2</id>
<x>450</x>
<y>70</y>
<c>0x0000FF</c>
<m>75</m>
</ball>
</balllist>

The XML file is then loaded using the following AS3 code. The data from the XML file is stored into an array “b” so that it can be easily accesssed and modified within the program.

var b : Array = new Array();
var loader : URLLoader = new URLLoader(); // used to load xml file
var xml : XML; // used to store XML data

loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(new URLRequest("balls.xml"));

// gets executed when xml data has been loaded
function loadXML(e : Event) : void {

var i : int;
var n : int;

xml = new XML(e.target.data);
xml.ignoreWhitespace = true;
n = xml.ball.length(); // # of balls in XML file
// load xml data into ball array
for (i = 0; i < n; i++) {
b[i].x = xml.ball[i].x;
b[i].y = xml.ball[i].y;
b[i].c = xml.ball[i].c;
b[i].m = xml.ball[i].m;
}
}

To save the file, I just created a big string containing the XML code and sent it to a PHP routine via the “POST” method:

// saves the xml
function saveXML(e : Event) : void {

var s : String; // string containing XML
var h : String; // string to create a hexadecimal value for colours
var i : int;

// create xml as a string
s = '<balllist>n';
for (i = 0; i < b.length; i++) {
s = s + "t<ball>n";
s = s + "tt<id>" + i + "</id>n";
s = s + "tt<x>" + b[i].x + "</x>n";
s = s + "tt<y>" + b[i].y + "</y>n";
h = b[i].c.toString(16);
while (h.length < 6) {
h = "0" + h;
}
s = s + "tt<c>0x" + h + "</c>n";
s = s + "tt<m>" + b[i].m + "</m>n";
s = s + "t</ball>n";
}
s = s + "</balllist>";

// pass string to php routine which saves the data, using POST method
var req : URLRequest = new URLRequest();
var loader : URLLoader = new URLLoader();

req.data = s;
req.contentType = "text/xml";
req.method = URLRequestMethod.POST;
req.url = "SaveXML.php";
loader.load(req);
}

Finally I created a really simply PHP routine and saved it in a file called “SaveXML.php”. It simply dumps all of the text which was passed to it from Flash into the “balls.xml” file. Here is the code:

<?php

// simple routine to save xml file
// passed a large string from flash using post method

if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$xml = $GLOBALS["HTTP_RAW_POST_DATA"];
$file = fopen("balls.xml","wb");
fwrite($file, $xml);
fclose($file);
}

?>

Leave a Reply