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 colour. When you are finished you can click on "save" which saves your work into an XML file. The next time you visit this site, the demo will load the balls from the XML file that was last saved.
The Code
In order to store information about the ball's coordinates, colour and size I used the following XML format which is saved in a file called "balls.xml":
<x>80</x>
<y>50</y>
<c>0xFF0000</c>
<m>50</m>
<ball>
<x>330</x>
<y>150</y>
<c>0x00FF00</c>
<m>100</m>
<ball>
<x>450</x>
<y>70</y>
<c>0x0000FF</c>
<m>75</m>
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 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].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:
function saveXML(e : Event) : void {
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\t<id>" + i + "</id>\n";
s = s + "\t\t<x>" + b[i].x + "</x>\n";
s = s + "\t\t<y>" + b[i].y + "</y>\n";
h = b[i].c.toString(16);
while (h.length < 6) {
s = s + "\t\t<c>0x" + h + "</c>\n";
s = s + "\t\t<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:
// simple routine to save xml file
// passed a large string from flash using post method
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$file = fopen("balls.xml","wb");
fwrite($file, $xml);
fclose($file);
?>