Create/Edit XML with Flex and PHP (part 2/2)

This is the second part of the Flex-PHP-XML tutorial, in which I’ll show you how to delete nodes from an XML and thus making it work like a database.

  • First we need to have something in our XML so lets assume the following content:
  • <?xml version=”1.0″ encoding=”UTF-8″?&gt
    <music&gt
    <newItemID&gt
    <titleID>very soon.mp3</titleID&gt
    <urlID>http://www.filerecycle/music/very soon.mp3</urlID&gt
    <dateID>9/8/2009</dateID&gt
    <descriptionID>delete fodder…</descriptionID&gt
    </newItemID&gt
    <newItemID id=”2625″&gt
    <titleID>id.mp3</titleID&gt
    <urlID>http://www.filerecycle/music/id.mp3</urlID&gt
    <dateID>10/8/2009</dateID&gt
    <descriptionID>song?</descriptionID&gt
    </newItemID&gt
    </music&gt

  • Now some MXML for the call to PHP
  • <mx:Button label=”Remove Item from List” width=”150″ height=”50″ top=”150″ styleName=”ButtonRem” click=”filePop();” horizontalCenter=”180″ fontSize=”10″ fontWeight=”bold”/&gt

  • and the HTTP Service Request assuming a datagrid named “infoMus” which holds our data from the XML:
  • <mx:HTTPService id=”filePop” showBusyCursor=”true” url=”assets/xmlRemover.php” headers=”null” requestTimeout=”18″ resultFormat=”e4x”
    contentType=”application/x-www-form-urlencoded” method=”GET” result=”resultHandle(event)”>
    <mx:request>
    <id>{infoMus.selectedItem.id}</id&gt
    </mx:request&gt
    </mx:HTTPService&gt

  • And finally the PHP code that does the heavy lifting:
  • <?php
    $file=”music.xml”;
    $xml=simplexml_load_file($file) or die (“Unable to load XML”);

    $keyToKill = null;

    $counter = 0;
    foreach ( $xml->newItemID as $node => $nodeObject)
    {
    $attr = $nodeObject->attributes();

    if ( $attr[‘id’] == $_GET[‘id’])
    {
    $itemToKill = $counter;
    break;
    }
    ++$counter;
    }
    echo “Key that will be removed:{$_GET[‘id’]}|{$itemToKill}”;
    unset($xml->newItemID[$itemToKill]);

    $doc = new DOMDocument(‘1.0’);
    $doc->loadXML( $xml->asXML());
    $doc->preserveWhiteSpace = false;
    $doc->formatOutput = true;
    file_put_contents( $file, $doc->saveXML());
    ?&gt

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin

    Create/Edit XML with Flex and PHP (part 1/2)

    This project of creating and editing an XML through Flex and PHP took me several days to figure out and gather all the info I wanted, and because there isn’t anything really helpfull out there I decided to make this post so that there is at least one viable piece of code for people to learn on.
    So on to the code:

    //in this example the structure that we will create is like this and stored in a file named “music.xml”:
    //<music&gt
    //<newFile&gt
    //<id>…</id&gt
    //<title>…</title&gt
    //<urlID>…</urlID&gt
    //<descriptionID>…</descriptionID&gt
    //<dateID>…</dateID&gt
    //</newFile&gt
    //…
    //
    // have in mind that the initial tag has already been created and we
    // add the nodes in there
    //we create the http request that will transfer the data to the php file upon call

    <mx:HTTPService id=”filePush” showBusyCursor=”true” url=”assets/xmlWriter.php” headers=”null” requestTimeout=”18″ resultFormat=”e4x”
    contentType=”application/x-www-form-urlencoded” method=”GET”&gt
    <mx:request&gt
    <id>{getID()}</id&gt
    <title>{titlePush.text}</title&gt
    <url>{urlString+titlePush.text}</url&gt
    <date>{date_str}</date&gt
    <desc>{desc.text}</desc&gt
    </mx:request&gt
    </mx:HTTPService&gt

    //now we throw in some Action script
    //to create a unique id for all entries

    public function getID():Number
    {

    var start:Number=Math.round(Math.random()*today_date.getFullYear());
    start=(start+(today_date.getMonth()+1)+today_date.getDay())*today_date.getSeconds();
    return start;
    }

    //and for the Date

    [Bindable]
    public var today_date:Date = new Date();
    public var date_str:String = (today_date.getDate()+”/”+(today_date.getMonth()+1)+”/”+today_date.getFullYear());

    //==========================================
    //and finaly the PHP code, pretty straightforward using SimpleXML:

    <?php
    $file=”music.xml”;
    $xml=simplexml_load_file($file) or die (“Unable to load XML”);
    $vitals = $xml->addChild(‘newItemID’);
    $vitals->addAttribute(‘id’, $_GET[‘id’]);
    $vitals->addChild(‘titleID’, stripcslashes($_GET[‘title’]));
    $vitals->addChild(‘urlID’, $_GET[‘urlID’]);
    $vitals->addChild(‘dateID’, $_GET[‘date’]);
    $vitals->addChild(‘descriptionID’, stripcslashes($_GET[‘desc’]));

    $doc = new DOMDocument(‘1.0’);

    $doc->preserveWhiteSpace = false;
    $doc->loadXML( $xml->asXML());
    $doc->formatOutput = true;

    file_put_contents( $file, $doc->saveXML());

    ?&gt

    for the editing part wait for my next post which won’t be too late!
    Enjoy!

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin

    How to make Combobox with hours of day (quarters)

    This is an algorithm which produces the hours of day for every quarter (00:00, 00:15, 00:30, 00:45) and inserts them in a combobox, I used this in my ToDo application which I will soon post and I thought it might be useful to someone.

    /*ActionScript*/

    var model:Array = [];

    var entry:Number = 0;
    var entryHour:Number = 0;
    var entryMinutes:Number = 0;
    var result:String;

    //The main loop runs 4*24 times cause we want all hours from 00:00 – 24:00 to be set
    //
    for (var j:int = 0; j<4*24; j++) { if (j==0)
    {

    model.push(result=(entryHour=entryHour).toString()+”0″+”:”+”00″);
    }
    else if (entry<3)
    {
    if(entryHour<10)
    {

    //if time < 10 adds a 0 so it will look like 09:00 and not 9:00
    model.push(result = “0”+(entryHour).toString()+”:”+(entryMinutes=entryMinutes+15).toString());
    }
    else
    {
    model.push(
    result = (entryHour).toString()+”:”+(entryMinutes=entryMinutes+15).toString());
    }

    entry++;

    }
    else
    {
    if(entryHour<9)
    {
    model.push(result= “0”+(entryHour=entryHour+1).toString()+”:”+”00″);
    }
    else
    {
    model.push(result=(entryHour=entryHour+1).toString()+”:”+”00″);
    }

    //reset the vars
    entry=0;
    entryMinutes=0;

    }
    }

    return model;
    }

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin

    Communicate with JavaScript, send-receive

    Actually its quite simple to communicate with Javascript from Flash, simply by importing the externalInterface library. The following code displays a simple use, from which the Javascript “reads” the available space within the browser window and sends it to the flex application, which draws a panel to match this space, so you can have a full screen application no matter the screen resolution and/or browser…

    &lt?xml version=”1.0″ encoding=”utf-8″?&gt

    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” viewSourceURL=”srcview/index.html”&gt

    <mx:Script&gt
    &lt![CDATA[
    import mx.controls.Alert;
    import mx.events.*;
    import mx.controls.*;
    import flash.external.*;

    public var w:uint;
    public var h:uint;
    public function callWrapper(event:MouseEvent):void
    {

    var jsWidth:String = “getWidth”;
    var jsHeight:String = “getHeight”;
    w = ExternalInterface.call(jsWidth);
    h = ExternalInterface.call(jsHeight);
    //testPanel.width=w/2;
    //testPanel.height=h/2;
    Alert.show(w.toString()+”*”+h.toString());
    resizeMe.widthTo=w;
    resizeMe.heightTo=h;
    resizeMe.play();
    }

    public function original():void
    {
    resizeMe.widthTo=200;
    resizeMe.heightTo=300;
    resizeMe.play();
    }
    ]]>
    &lt/mx:Script&gt

    <mx:Resize id=”resizeMe” target=”{testPanel}”/&gt

    <mx:Canvas height=”100%” width=”100%”&gt

    <mx:Button label=”Expand!” click=”callWrapper(event);” horizontalCenter=”0″/&gt

    <mx:Panel id=”testPanel” width=”200″ height=”300″ backgroundColor=”#BDE018″ y=”0″ x=”0″ borderStyle=”none”&gt
    <mx:Button label=”Return” click=”original();”/&gt
    &lt/mx:Panel&gt

    &lt/mx:Canvas&gt

    &lt/mx:Application&gt

    add this 2 functions to your html that contains the produced .swf

    <script language=”JavaScript” type=”text/javascript”&gt

    function getWidth() { return document.body.clientWidth; }
    function getHeight() { return document.body.clientHeight; }

    View working example here

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin

    Applying an effect to a popup in Flex (open,close)

    This is an effect I made to make popups appear and disappear in a cooler way…

    u can view an example here right click for source code…

    also posting the code here just in case…

    the mxml code for the main application:

    <?xml version=”1.0″ encoding=”utf-8″?>
    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” viewSourceURL=”srcview/index.html” backgroundColor=”0xffffff”>

    <mx:Script>
    <![CDATA[
    import mx.effects.easing.*;
    import mx.events.CloseEvent;
    import mx.managers.PopUpManager;

    private function launchDiag1():void
    {
    var win:diagBox = PopUpManager.createPopUp(this, diagBox, true) as diagBox;
    PopUpManager.centerPopUp(win);
    }
    ]]>
    </mx:Script>

    <mx:Canvas height=”100%” width=”100%”>

    <mx:Button click=”launchDiag1()” label=”Play!” verticalCenter=”0″ left=”50″ height=”80″ width=”100″/>

    </mx:Canvas>
    </mx:Application>

    //=================================================

    Now the popup code: ( create a new mxml component first, and name it diagBox)

    <?xml version=”1.0″ encoding=”utf-8″?>
    <!– diagBox.mxml –>

    <mx:TitleWindow xmlns:mx=”http://www.adobe.com/2006/mxml”
    layout=”vertical”
    showCloseButton=”true”
    width=”550″
    height=”500″
    close=”titleWindow_close();” backgroundAlpha=”0.0″ borderAlpha=”0.0″ creationComplete=”openingEffect.play();”
    shadowDirection=”center” shadowDistance=”0″ borderStyle=”none”>

    <mx:Script>
    <![CDATA[
    import mx.events.EffectEvent;
    import mx.events.CloseEvent;
    import mx.managers.PopUpManager;
    import mx.effects.easing.*;

    private function titleWindow_close():void {
    shutdownEffect.play();

    }

    public function endDiag():void
    {
    PopUpManager.removePopUp(this);
    }
    ]]>
    </mx:Script>

    <mx:Style>
    .header
    {
    color:#ffffff;
    }
    </mx:Style>

    <mx:Sequence id=”openingEffect” target=”{panel}” effectStart=”panel.visible=true”>
    <mx:Pause duration=”400″/>
    <mx:Resize id=”expand” widthTo=”500″ duration=”300″ easingFunction=”Circular.easeOut”/>
    <mx:Pause duration=”300″/>
    <mx:Resize id=”expand2″ heightTo=”450″ duration=”300″ easingFunction=”Circular.easeInOut”/>
    </mx:Sequence>

    <mx:Sequence effectEnd=”endDiag();” id=”shutdownEffect” target=”{panel}” suspendBackgroundProcessing=”true”>
    <mx:Pause duration=”400″/>
    <mx:Resize id=”contract2″ heightTo=”1″ duration=”300″ easingFunction=”Circular.easeInOut” suspendBackgroundProcessing=”true”/>
    <mx:Pause duration=”300″ suspendBackgroundProcessing=”true”/>
    <mx:Resize id=”contract” widthTo=”1″ duration=”300″ suspendBackgroundProcessing=”true” easingFunction=”Circular.easeOut”/>
    </mx:Sequence>

    <mx:Canvas height=”100%” width=”100%”>

    <mx:Panel id=”panel” visible=”false” height=”1″ width=”1″ borderColor=”#000000″ horizontalCenter=”0″ verticalCenter=”0″
    title=”Early Years…” themeColor=”#ffffff” autoLayout=”true” titleStyleName=”header”>

    <mx:Text id=”info” text=”Sample Text containing the phrase: Hello World! “/>

    </mx:Panel>
    </mx:Canvas>

    </mx:TitleWindow>

    Enjoy!

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin