read xml content before saving to it
Actionscript:
var txtFld:TextField = new TextField();
txtFld.width = 500;
txtFld.height = 350;
txtFld.multiline = txtFld.wordWrap = true;
addChild(txtFld);
var str:String = "<user>1";
str += "<value>Sent from ActionScript</value>";
str += "<value>Sent from ActionScript</value>";
str += "<value>Sent from ActionScript</value>";
str += "</user>";
var xmlToSend:XML = new XML(str);
var req:URLRequest = new URLRequest("save_xml.php");
req.data = xmlToSend;
req.contentType = "text/xml";
req.method = URLRequestMethod.POST;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
urlLoader.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
urlLoader.load(req);
function onIOError(evt:IOErrorEvent):void
{
txtFld.text = "XML load error.\n" + evt.text;
}
function onComplete(evt:Event):void
{
try
{
urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
urlLoader.removeEventListener(Event.COMPLETE, onComplete);
var loadedXML:XML = new XML(evt.target.data);
txtFld.text = loadedXML;
}
catch (err:Error)
{
txtFld.text = "XML parse error:\n" + err.message;
}
}
PHP:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$data = $GLOBALS["HTTP_RAW_POST_DATA"];
$file = fopen("data.xml","wb");
fwrite($file, $data);
fclose($file);
}
?>
This actionscript/php basically creates the data.xml file if it doesn't exist yet and adds the content of the 'str' string to it. The 'user' tag with some 'value' tags between them. In this case user nr 1. The script opens the data.xml file (or creates it the 1st time), writes the xml data in it received from Flash and closes the file.
That's not entirely how I want to make it work. I want it to open the data.xml file, then check how many 'user' tags there are at that moment. Then it should add the 'str' string to it, but with the 'user' tag having a value of the number of 'user' tags currently in the data.xml file plus one. So if the script reads the data.xml file first and sees that currently there are 3 user tags in it, the content added to it should be:
var str:String = "<user>4";
str += "<value>Sent from ActionScript</value>";
str += "<value>Sent from ActionScript</value>";
str += "<value>Sent from ActionScript</value>";
str += "</user>";
How can I do this? I'm guessing the php script should first return the content of the data.xml file. So Flash can get the number of user tags back so it can put together the correct str string with 1 added to the number of users. And then send that string back to php in order to write and close the file?