Flex, PHP and XML - a tutorial

Ok, so here's our stripped down php file:

PHP:
  1. <?php
  2. header("Content-type: text/xml");
  3.     include 'library/config.php';
  4.     include 'library/opendb.php';
  5.     $result = mysql_query("select * from data", $conn) or die('Error, query failed');
  6.     mysql_close($conn);
  7.     $xml_output = "<?xml version=\"1.0\"?>\n";
  8.     $xml_output .= "<bikes>\n";
  9.     for ( $x = 0 ; $x <mysql_num_rows ( $result ) ; $x ++ ) {
  10.         $row = mysql_fetch_assoc($result);
  11.         $xml_output .= "\t<bike>\n" ;
  12.         //$xml_output .= $row['year'];
  13.         $xml_output .= "\t\t<year>" . $row['year'] . "</year>\n";
  14.         $xml_output .= "\t\t<make>" . $row['make'] . "</make>\n";
  15.         $xml_output .= "\t\t<model>" . $row['model'] . "</model>\n";
  16.         $xml_output .= "\t</bike>\n";
  17.     }
  18.     $xml_output .= "</bikes>";
  19.     echo $xml_output;
  20. ?>

The only major change from the first example is the header, we want Flex to think this file is xml, the rest of the changes are just removing all the HTML.

So, on to the Flex, 3 chunks again, the first is our HTTPService's, then we add a few actionscript functions, finally we finish off with our layout code.

XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="loadApp ( )">
  3.    
  4.     <mx:HTTPService id="load_data"  url="return_xml.php5" result="loadData ( event )" />
  5.    
  6.     <mx:HTTPService id="send_data" result="checkResult ( event )" method="POST" url="add_row_bike.php5" useProxy="false">
  7.         <mx:request xmlns="">
  8.             <year> { year.text } </year>
  9.             <make> { make.text } </make>
  10.             <model> { model.text } </model>
  11.         </mx:request>
  12.     </mx:HTTPService>

When you create a new Flex project in Flex builder it writes the first 2 lines for you, what you need to add to the Application tag is the applicationComplete call, this is called once the swf has loaded and is the entry point for our Actionscript logic. The first HTTPService "load_data" is what will be called first and returns the table as formatted XML, this has a result attribute which is a reference to a method in our Actionscript, will go into detail about that later, but for now all we need to know is the we pass "event", which is what's returned by return_xml.php. The second HTTPService is what we what to call when add a bike, the attributes are fairly self explanatory, the request is the MXML equivalent of our form elements in the HTML example. It's saying, what will this HTTPService when it POST's? So we give it references to out TextInputs, which we'll cover later.

ACTIONSCRIPT:
  1. <mx:Script>
  2.         <![CDATA[
  3.         import mx.rpc.events.ResultEvent ;
  4.        
  5.         private var _bikeData : Object ;
  6.        
  7.         private function loadApp ( ) : void {
  8.             load_data.send ( ) ;
  9.         }
  10.        
  11.         private function loadData ( evt : ResultEvent ) : void {
  12.             _bikeData = evt.result.bikes.bike ;
  13.             bikeGrid.dataProvider = _bikeData ;
  14.         }
  15.        
  16.         private function sendData ( ) : void {
  17.             send_data.send ( ) ;
  18.         }
  19.        
  20.         private function checkResult ( evt : ResultEvent ) : void {
  21.             bikeGrid.dataProvider = evt.result.bikes.bike ;
  22.             year.text = "" ;
  23.             make.text = "" ;
  24.             model.text = "" ;
  25.         }
  26.         ]]>
  27.     </mx:Script>

The next chunk is our AS 3, we start with an import, if you haven't used AS 3 yet, prepare yourself for lots of imports, it's just how it is in AS 3. Then we declare a private variable with type Object, this is what's going to store the data we receive from our HTTPService. Next we have our loadApp method, this is called by applicationComplete and in term calls our load_data HTTPService. When load_data gets a result it calls our loadData method which assigns the event data to our variable, and then the variable as the data provider for our data grid. The sendData method is called from our Button and calls our send_data HTTPService. The final method checkResult is called when send_data gets a valid result is passed the event data, again assigns that as the data provider of our data grid and empties our text fields.

XML:
  1. <mx:Panel paddingTop="10" paddingRight="10" paddingBottom="10" paddingLeft="10" title="Bike Chooser" width="100%" height="100%">
  2.         <mx:VDividedBox x="0" y="0" width="100%" height="100%">
  3.             <mx:DataGrid dataProvider="_bikeData" width="100%" height="442" id="bikeGrid">
  4.                 <mx:columns>
  5.                     <mx:DataGridColumn headerText="Year" dataField="year"/>
  6.                     <mx:DataGridColumn headerText="Make" dataField="make"/>
  7.                     <mx:DataGridColumn headerText="Model" dataField="model"/>      
  8.                 </mx:columns>
  9.             </mx:DataGrid>
  10.             <mx:Form height="140">
  11.                 <mx:FormItem label="Year">
  12.                     <mx:TextInput id="year" />
  13.                 </mx:FormItem>
  14.                 <mx:FormItem label="Make">
  15.                     <mx:TextInput id="make" />     
  16.                 </mx:FormItem>
  17.                 <mx:FormItem label="Model">
  18.                     <mx:TextInput id="model" />
  19.                 </mx:FormItem>
  20.                 <mx:FormItem>
  21.                     <mx:Button click="sendData()" label="Submit" />
  22.                 </mx:FormItem>
  23.             </mx:Form>
  24.         </mx:VDividedBox>
  25.     </mx:Panel>
  26. </mx:Application>

Our last chuck of code in Flex is the layout code, one of the beauties of Flex is the speed by which you can throw together a layout. It's pretty basic - Panel, VDividedBox, DataGrid with labeled columns, Form with FormItems labeled, Button with a click method.

So, thats it, you should be able to Run the app from your webserver and enter data and it should refresh on the fly.

Download the zip with example code.

The next thing I'd like to do is to get the whole thing working through AMF PHP and eventually maybe even Ruby on Rails.

If you've found this helpful please link or comment below.

Jolyon

Pages: 1 2

Socialise this post, find out more about the Socializer plugin for WordPress.

6 Responses to “Flex, PHP and XML - a tutorial”  

  1. 1 paddy

    cheers Jolyon, I have an idea for my first flex app and I’m sure this tut will give me a good head start. The app will be an internal video sharing system for my fellow employees. We’re all going to pool our videos/DVDs so we can borrow each others! I’ll let you know how well it works…

    best paddy ;)

  2. 2 Richard Leggett

    Nice one Jolyon, a couple more of these and get this on MXNA!! It’s been a while since we saw comprehensive walkthrough tuts like this, a few years since these have been popular and god knows thats how I learned it, so congrats.

  3. 3 Matthew Ryan

    This is a great post and Flex-PHP example. Simple yet perfect as an example to build up from.

    Best regards,

    Matthew
    Brisbane, Australia

  4. 4 bintar

    hi there,
    this seems a great example. But when i tried it, i got error message like :
    ReferenceError: Error #1065: Variable _bikeData is not defined.
    at global/flash.utils::getDefinitionByName()
    at mx.utils::DescribeTypeCache$/describeType()
    at mx.utils::ObjectUtil$/getClassInfo()
    at mx.controls::DataGrid/::generateCols()

    can somebody help me about this ?
    thanks

  5. 5 Jolyon

    Hi Bintar,

    I’m sorry to hear you’re having trouble.

    If you zip up the whole project and post it on a webserver somewhere I’ll take a look at your code, just post the link up as another comment.

    I’ll try and get back to you as soon as possible.

    Jolyon

  6. 6 Martin

    Finally found a tut I can understand and is complete :)!

    Thanks!!

Leave a Reply