Actionscript -> JSON -> PHP

Posted in Flex/ActionScript on December 23rd, 2009 by admin – Be the first to comment

Lately I have been using a tool a lot that I wrote some months ago, so I thought I better share it with the rest of the world. It’s a tool for sending and receiving Objects between a Flash/Flex client and a PHP server.


function objectFromServer(url:String, data:Object, handler:Function):void {
    var loader:URLLoader = new URLLoader();
    var requester:URLRequest = new URLRequest();
    requester.method = URLRequestMethod.POST;
    loader.addEventListener(Event.COMPLETE, function(event:Event):void {
        var tempLoader:URLLoader = URLLoader(;
        var obj:Object = JSON.decode(;
    loader.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void {"ioErrorHandler: " + event);
    loader.dataFormat = URLLoaderDataFormat.TEXT;
    requester.url = url;
    var variables:URLVariables = new URLVariables();
    variables.json = JSON.encode(data); = variables;

You will need to download as3corelib.swc from and add it to your project’s libary path.
This is how you add it in Flex Builder: Properties->Flex Build Path->Libary path->Add SWC…

I have written a simple test program to show how objectFromServer is used.


setInterval(function():void {
    objectFromServer("/tests/objectFromServer.php", {name: "Mikkel"}, function(o:Object):void {
        myLabel.text = o.text as String;
}, 3000);


$o = json_decode($_POST["json"]);
$result = array("text" => "Hello ".$o->name.", server time is " . time());
echo json_encode($result);


The Flash plugin is required to view this object.