3.03.2010

AS3 Tip of the Day - Saving XML/text using Flash/PHP

This tutorial will show how to save XML or TEXT file in your server using FLASH and PHP.

This is very helpful to me and I have used this many times. In one of my first project using this kind of functionality, I researched in the net, and found this solution.

AS3:

// declaring var xmlcontents String. You should set this first.
var xmlcontents:String = "this is the xml contents to be saved in your xml."

// declaring var foldername String. This is the folder container of the saved XML file
var foldername:String = "myXML."

// declaring var filename String. This is the filename of the XML file
var filename:String = "test.xml."

// declaring var dataPass URLVariables
var dataPass:URLVariables = new URLVariables();

// declaring var urlLoader URLLoader
var urlLoader:URLLoader = new URLLoader();

// declaring var previewRequest URLRequest
var previewRequest:URLRequest = new URLRequest(Main.SERVER_PATH + "saving-xml.php");

// i used method "post" in this sample. you can edit this
previewRequest.method = URLRequestMethod.POST;

// setting dataPass variables to be passed to PHP
dataPass.filename = filename;
dataPass.xmlcontents = xmlcontents;
dataPass.foldername = foldername;

// passing dataPass data PHP
previewRequest.data = dataPass;

// calling the PHP or loading the PHP
urlLoader.load(previewRequest);


PHP:

// POST variable
$fileName = $_POST["filename"];

// POST variable
$xmlContents = $_POST["xmlcontents"];

// backslashes from xml string (skip this for plain text)
$lastBackslashPos = strpos ($xmlContents, "\\");
while($lastBackslashPos >0){
$xmlContents = substr($xmlContents,0,$lastBackslashPos)
.substr($xmlContents,$lastBackslashPos+1,strlen($xmlContents));
$lastBackslashPos = strpos ($xmlContents, "\\");
}

// POST foldername
$foldername = $_POST["foldername"];

// test if the folder name is existing in the server (skip this if you want to test in server path)
if(!is_dir($foldername . "/")) {
mkdir($foldername . "/", 0755);
}

// write xml data to file on server relatively to server path of the this PHP file
$fh = fopen($foldername . "/" . $fileName, "w");
fwrite($fh, $xmlContents);
fclose($fh);
?>

Many thanks to Google.

No comments:

Post a Comment