One of the main abilities of an Web application must be its communication with the server, the posibility to send data to the server and to receive a reply from it.
Flash, through ActionScript can send data to server and receive its response.
- In this tutorial it is presented the method to send XML data from ActionScript to a PHP script, with a Flash presentation (SWF).


So, to send XML data with ActionScript to a PHP script, follow these steps:
  1. In ActionScript, define a variable (String type) in which add the XML content, as a string.
  2. Create a URLRequest instance with the URL address of the PHP script (the Flash presentation and the PHP script must be on the same server).
  3. Use the data property to add in this instance the XML content stored in the String variable. With the contentType property set the type as "text/xml", and apply URLRequestMethod.POST to the method property (this sets the transfer method).
  4. Define an URLLoader object that will send the XML (in string format), and also will receive the reply from the server.
  5. Register to this object's instance an event listener with the Event.COMPLETE event (used to detect when a reply was received from the server). Register also another event listener with the IOErrorEvent.IO_ERROR event (to detect any error that could appear during the data transfer).
  6. Define the functions that must be called by these registered events, and a text field in which to display the response from the PHP script.
  7. The last step, apply the load() function to the "URLLoader" object, with the XML content in argument.

Below is an ActionScript code with these instructions and a PHP script that will receive and save the XML in a file on the server (in a folder named "xmls").
- You can find more detailed explanations in the comments in each script.
- Note:
    First, create the "xmls" folder on the server, in the same place as the PHP script, and also give writting permission in this folder, by setting CHMOD 0777 (if it's on Linux).

The ActionScript code

// http://coursesweb.net/flash

// define a Text field that will display the reply from the PHP
var respTxt:TextField = new TextField();

// declare a variable that will store the reply from the PHP
var re_server:XML;

// Here you can load external XML content and edit it, then convert it into String, with toXMLString()

// The String with the XML data
var xml_str:String = '<?xml version="1.0" encoding="UTF-8"?><root><value>coursesweb.net</value></root>';

// Define an object with the URL of the PHP file, add the XML, and the method of transfer
var php_url:URLRequest = new URLRequest("savexml.php");       // Object with the file's adress
php_url.data = xml_str;                                   // Add the XML string
php_url.contentType = "text/xml";                         // Define the type of the content
php_url.method = URLRequestMethod.POST;                   // Sets transfer method - POST

var obj_send_load:URLLoader = new URLLoader();          // the instance that will expedite the data

// Register the Event listener that detects when the data was completely transferred and the reply is received
obj_send_load.addEventListener(Event.COMPLETE, onComplete, false, 0, true);

// Register the Event that is triggered in case of error in transfer
obj_send_load.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);

// Function called by the event triggered when the transfer was finished
function onComplete(evt:Event):void
{
  // Uses try..catch to retain and customize possible errors
  try
  {
    re_server = XML(evt.target.data);        // store in as XML object the reply from the PHP
    respTxt.text = re_server;                // Add in the text field the server response
  }
  catch (err:TypeError)
  {
    // If any error is generated, it will retain it and include it in the text field
    respTxt.text = "Error when processing the reply from the server:\n" + err.message;
  }

  // Delete the event listeners, to free up memory
  removeEventListener(Event.COMPLETE, onComplete);
  removeEventListener(IOErrorEvent.IO_ERROR, onIOError);

  placeText();       // Calls the function that displays the text field
}

// Function called by the event triggered in case of a transfer error
function onIOError(evt:IOErrorEvent):void
{
  // captures the error, customizes it and adds it in the text field
  respTxt.text = "Error sending XML data.\n" + evt.text;

  placeText();        // Calls the function that displays the text field
}

// Function that displays the text field in the Flash presentation
function placeText():void
{
  // define properties for the text area (distance, multiline, alignment, border)
  respTxt.x = 5;
  respTxt.y = 15;
  respTxt.multiline = true;
  respTxt.autoSize = TextFieldAutoSize.LEFT;
  respTxt.border = true;

  addChild(respTxt);        // Add the text field in Flash
}

// apply the load() method to expedite data (added in argument)
obj_send_load.load(php_url);

The PHP Code

<?php
// http://coursesweb.net

// sets tath and name of the XML file on the server
$xml_file = 'xmls/test.xml';

// gets the data received through POST (in string format)
$xml_data = $HTTP_RAW_POST_DATA;

// If the data in $xml_data is saved on the server (in the location specified in $xml_file)
// outputs them with a "echo" instruction
// If data cannot be saved, returns an error
 
if(file_put_contents($xml_file, $xml_data)) echo $xml_data;
else echo 'Error, the XML data could not be saved on the server, at'. $xml_file;
?>

• To test this script, copy the ActionScript code in a new Flash document (in the "Actions panel") and create the Flash presentation (the SWF file), from the menu File -> Export -> Export Movie.
Create a PHP file, named "savexml.php", and add in it the PHP code above. Or use the files from the archive that can be downloaded from the link at the end of this tutorial.
Copy the SWF file and the "savexml.php" on the server. In the same directory create a folder named "xmls" and give it CHMOD 0777 permissions.
Access in your browser the SWF file on the server (e.g.: http://server/file_name.swf ).
In the browser should appear a Flash presentation with a text field which displays the XML data sent to PHP, as you can see below. Also, in the "xmls" folder on the server you can find a file "test.xml".
<root>
    <value>coursesweb.net</value>
</root>

In ActionScript you can load and use an XML content from an external file, and process it before sending it to the PHP script.
It is important to convert the XML format into string before sending it.
- See the lessons from the ActionScript 3 section to learn about loading and processing XML data in Flash.


The archive with the FLA file, SWF presentation and the PHP script can be downloaded from: XML data from ActionScript to a PHP script.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Click on the HTML tag which creates an horizontal line in web page.
<br /> <em> <hr />
Some content ...
<hr />
Content under line ...
Which CSS property defines the text color?
font-style font-variant color
h2 {
  color: #cbdafb;
}
Click on the function which searches if a character, or text exists in a string.
indexOf() toString() split()
var str = "Web courses - http://CoursesWeb.net/";
if(str.indexOf("http://") == -1) alert("http:// isn`t in string");
else alert("http:// is in string");
Which function splits a string into an array of strings based on a separator?
array_merge() explode() implode()
$str = "apple,banana,melon,pear";
$arr = explode(",", $str);
var_export($arr);      // array (0=>"apple", 1=>"banana", 2=>"melon", 3=>"pear")
XML data from ActionScript to a PHP script

Last accessed pages

  1. PHP MySQL - WHERE and LIKE (15388)
  2. Zoo Amigos (6958)
  3. jQuery ajax() method (13427)
  4. Selection Tools (4056)
  5. Texarea with buttons to format text, colors and smiles (2773)

Popular pages this month

  1. Qwop (3462)
  2. Drag Racer V3 (1707)
  3. Flash Games - Free online Games (810)
  4. Bubbles3 (810)
  5. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (758)