Dynamically loading XML files using the HTTPService tag

In previous examples, “Creating a simple image gallery with the Flex TileList control” and “Creating a simple image gallery with the Flex HorizontalList control”, we saw how you could create a simple image gallery using the TileList and HorizontalList controls.

The following example shows how you can load XML files using the HTTPService tag so that you can dynamically load different galleries.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/29/dynamically-loading-xml-files-using-the-httpservice-tag/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;

            private var alert:Alert;

            private function loadGallery(src:String):void {
                httpService.url = src;
                httpService.send();
            }

            private function httpService_fault(evt:FaultEvent):void {
                var title:String = evt.type + " (" + evt.fault.faultCode + ")";
                var text:String = evt.fault.faultString;
                alert = Alert.show(text, title);
                xmlListColl.removeAll();
            }

            private function httpService_result(evt:ResultEvent):void {
                var xmlList:XMLList = XML(evt.result).images.image;
                xmlListColl = new XMLListCollection(xmlList);
            }
        ]]>
    </mx:Script>

    <mx:XMLListCollection id="xmlListColl" />

    <mx:HTTPService id="httpService"
            resultFormat="e4x"
            fault="httpService_fault(event);"
            result="httpService_result(event)" />

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="gallery 1"
                click="loadGallery('gallery1.xml');" />
        <mx:Button label="gallery 2"
                click="loadGallery('gallery2.xml');" />

        <mx:Button label="gallery 404"
                click="loadGallery('gallery404.xml');" />
    </mx:ApplicationControlBar>

    <mx:TileList id="tileList"
            dataProvider="{xmlListColl}"
            itemRenderer="TileListItemRenderer"
            columnCount="3"
            columnWidth="150"
            rowCount="2"
            rowHeight="100" />

</mx:Application>

TileListItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/29/dynamically-loading-xml-files-using-the-httpservice-tag/ -->
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Image source="{data.@src}"
            horizontalCenter="0"
            verticalCenter="0" />

    <mx:Label text="{data.@lbl}"
            fontWeight="bold"
            horizontalCenter="0"
            bottom="0" />

</mx:Canvas>

View source is enabled in the following example.

23 thoughts on “Dynamically loading XML files using the HTTPService tag

  1. Thanks for all your examples, they are very helpful! By chance, do you know to write to an xml-file from within Flex using PHP? Or maybe have a link to share? Would be nice use above code to read from xml and somehow be able to update thet xml-file dynamically also.

    Thanks again, very appreciated!
    /Benny

    1. Hi Michael,
      I’m just wondering if you or anyone here knows how to load multiple/dynamic xml files into the fla from php/asp
      Instead of doing the same old xml.load(‘myfile.xml’);, I want to load different xml files per user from a database for example. I have the php/asp code but not sure how to get flash to work with that.
      I guess I need some sort of parameter like xml.load(url:String) .
      I haven’t done AS2 in a while so it feels like it’s all new to me. Thanks for the help in advance.

  2. How do I reload the data of the XMLListCollection?

    <mx:HTTPService id="xml_httpservice_q1" url="q1.php?randomnumber=(randomnumber)" resultFormat="e4x"/>
    <mx:XMLListCollection id="xml_result_q1" source="{xml_httpservice_q1.lastResult.resultaat}"/>
    

    and on creationComplete: xml_httpservice_q1.send();

    I get the XML data, no problem there.

    when I perform xml_httpservice_q1.send(); a second time (I want to reload the data from the q1.php since it has changed), I receive the following error:

    warning: unable to bind to property ‘resultaat’ on class ‘XML’ (class is not an IEventDispatcher)

  3. I’m following up with this example but When I click the Button to load gallery. I get the Following error. I’m using Flex Builder 3.

    Error: Unable to load ”.
    at mx.controls::SWFLoader/loadContent()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1368]
    at mx.controls::SWFLoader/load()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1211]
    at mx.controls::SWFLoader/commitProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\SWFLoader.as:1015]
    at mx.core::UIComponent/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:5670]
    at mx.managers::LayoutManager/validateClient()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:791]
    at mx.controls.listClasses::TileBase/measureWidthOfItems()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\listClasses\TileBase.as:1860]
    at mx.controls.listClasses::TileBase/commitProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\listClasses\TileBase.as:2327]
    at mx.core::UIComponent/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:5670]
    at mx.managers::LayoutManager/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:519]
    at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:669]
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at mx.core::UIComponent/callLaterDispatcher2()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:8460]
    at mx.core::UIComponent/callLaterDispatcher()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\UIComponent.as:8403]

  4. Hi Peterd, first of all i want to thank you for all your great tutorials and example files, you are a life saver!!!
    I have modified this example of yours becouse i only want to load 1 gallery XML file.
    But i am experiencing much errors.
    I would like the TileList to load the “gallery1.xml”file automatic without the end-user clicking on the button.

    I really tried everything i thought would fix this, but no success.

    Thanks again, have a nice day.

    ————-
    Miguel Torres

  5. <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    		layout="vertical"
    		verticalAlign="middle"
    		backgroundColor="white">
    
    	<mx:Script>
    		<![CDATA[
    			import mx.rpc.events.ResultEvent;
    			import mx.rpc.events.FaultEvent;
    			import mx.controls.Alert;
    			import mx.events.ListEvent;
    			import mx.events.ItemClickEvent;
    			import flash.net.URLRequest;
    
    
    			private var alert:Alert;
    
    			private function loadGallery(src:String):void {
    				httpService.url = src;
    				httpService.send();
    			}
    
    			private function httpService_fault(evt:FaultEvent):void {
    				var title:String = evt.type + " (" + evt.fault.faultCode + ")";
    				var text:String = evt.fault.faultString;
    				alert = Alert.show(text, title);
    				xmlListColl.removeAll();
    			}
    
    			private function httpService_result(evt:ResultEvent):void {
    				var xmlList:XMLList = XML(evt.result).images.image;
    				xmlListColl = new XMLListCollection(xmlList);
    			}
    
    			private function tileList_itemClick(evt:ListEvent):void {
                var link:URLRequest = new URLRequest(evt.itemRenderer.data.@url);
    				navigateToURL(link);
    			}
    		]]>
    	</mx:Script>
    
    	<mx:XMLListCollection id="xmlListColl" />
    
    	<mx:Button label="gallery 1" click="loadGallery('gallery1.xml');" />
    
    	<mx:HTTPService id="httpService"
    			resultFormat="e4x"
    			fault="httpService_fault(event);"
    			result="httpService_result(event)" />
    
    
    	<mx:TileList id="tileList"
    			dataProvider="{xmlListColl}"
    			itemRenderer="TileListItemRenderer"
    			columnCount="3"
    			columnWidth="150"
    			rowCount="2"
    			rowHeight="100"
    			itemClick="tileList_itemClick(event);"/>
    
    </mx:Application>
    
  6. <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    		layout="vertical"
    		verticalAlign="middle"
    		backgroundColor="white">
    
    	<mx:Script>
    		<![CDATA[
    			import mx.rpc.events.ResultEvent;
    			import mx.rpc.events.FaultEvent;
    			import mx.controls.Alert;
    			import mx.events.ListEvent;
    			import mx.events.ItemClickEvent;
    			import flash.net.URLRequest;
    
    
    			private var alert:Alert;
    
    			private function loadGallery(src:String):void {
    				httpService.url = src;
    				httpService.send();
    			}
    
    			private function httpService_fault(evt:FaultEvent):void {
    				var title:String = evt.type + " (" + evt.fault.faultCode + ")";
    				var text:String = evt.fault.faultString;
    				alert = Alert.show(text, title);
    				xmlListColl.removeAll();
    			}
    
    			private function httpService_result(evt:ResultEvent):void {
    				var xmlList:XMLList = XML(evt.result).images.image;
    				xmlListColl = new XMLListCollection(xmlList);
    			}
    
    			private function tileList_itemClick(evt:ListEvent):void {
                var link:URLRequest = new URLRequest(evt.itemRenderer.data.@url);
    				navigateToURL(link);
    			}
    		]]>
    	</mx:Script>
    
    	<mx:XMLListCollection id="xmlListColl" />
    
    	<mx:Button label="gallery 1" click="loadGallery('gallery1.xml');" />
    
    	<mx:HTTPService id="httpService"
    			resultFormat="e4x"
    			fault="httpService_fault(event);"
    			result="httpService_result(event)" />
    
    
    	<mx:TileList id="tileList"
    			dataProvider="{xmlListColl}"
    			itemRenderer="TileListItemRenderer"
    			columnCount="3"
    			columnWidth="150"
    			rowCount="2"
    			rowHeight="100"
    			itemClick="tileList_itemClick(event);"/>
    
    </mx:Application>
    
  7. Hi,

    I have found a method to automaticly load de XML file without pressing the button. I thought post it in here for anybody who has the same problem as I had.

    I just added a creationComplete in the mx:Aplicaiton tag passing the “loadGallery (‘gallery1.xml’);”

    This might NOT be best practice, but for now its the only way I know to make it work.

    Again, thanks a lot for your great tuto┬┤s and examples.

  8. With the AdvancedDataGrid, if you bind an XMLListCollection to the dataProvider it works perfectly. However, if you bind the same XMLListCollection to the GroupCollection source so that you can do grouping and summary rows, it won’t seem to accept it and instead throws an error.

    To solve this, I switched my HTTPService from the format of “e4x” to “object” and it worked perfectly. Basically, you just need a more basic data source it seems like an array or object?

    Thought I’d note this since it took me a couple hours to figure out (yes, I’m new :)

    .:Joshua

  9. hi,

    i’ve tried inputting the code in Flex 3 but it has an error saying HTTP Request Error when i click on the gallery 1 link button. Any reason why?

    I would like the thumbnails to appear when the page is loaded, how do i go about doing that?

  10. <?php
    // Name: makegallery.php (PHP 5.x)
    // Who: Created by mallsop.com 10/18/2008
    // What: Dynamically get all photos in a folder and make an xml file.
    // Then name your gallery folder ‘mygallery’. Place this file there.
    // Licence: GPL.
    // How: Call this file instead of your xml file in your flex code.
    function scanDirectory($dirid, $dirname) {

    $return = “<”.”?xml version=\”1.0\” encoding=\”UTF-8\”?”.”>\n”;
    $return .= “<galleries>\n”;
    $return .= “<gallery id=\”$dirname\”>\n”;
    $return .= “<description>$dirname</description>\n”;

    while (($file = readdir($dirid)) != false) { // loop
    if (($file != “.”) && ($file != “..”)) { // isa file
    // get the file extension
    $break = explode(“.”, $file);
    $file_ext = $break[1];
    $file_ext_lowercase = strtolower($file_ext);
    if (($file_ext_lowercase == “gif”) OR ($file_ext_lowercase == “jpg”) OR ($file_ext_lowercase == “png”)) { // isa picture
    // $filename = $dirname.$file;
    $file_size = filesize($file);
    // sizes
    if ($file_size >= 1073741824) {
    $file_size = round($file_size / 1073741824 * 100) / 100 . ” gb”;
    }
    elseif ($file_size >= 1048576) {
    $file_size = round($file_size / 1048576 * 100) / 100 . ” mb”;
    }
    elseif ($file_size >= 1024) {
    $file_size = round($file_size / 1024 * 100) / 100 . ” kb”;
    }
    else {
    $file_size = $file_size . ” bytes”;
    }

    $return .= “<photo>\n”;
    $return .= “<name>$file</name>\n”;
    $return .= “<description>$file_size</description>\n”;
    $return .= “<source>$dirname/$file</source>\n”;
    $return .= “</photo>\n”;
    } // end isa picture
    } // end isa file to check
    } // end loop

    $return .= “</gallery>\n”;
    $return .= “</galleries>\n”;

    return ($return);
    } //end function

    // run script
    $path = getcwd();
    $dirname = basename($path); // “.”;
    $dirid = opendir(“.”);
    $results = scanDirectory($dirid, $dirname);
    closedir($dirid);
    // display the xml file on screen
    echo $results;
    // end of script
    ?>

  11. Hi,

    In my Flex applicatio im handling the Http Response that will be in a form of XML.
    I use to get the AttributeCollection from the event
    like

    var tempProjectData:ArrayCollection = event.result.Data.Project;

    It was working and i use this as a dataprovider for many components.

    But after my development i noticed that when i have only one record, then the event.result.Data is not an ArrayCollection. So im getting error.

    my xml looks like this

    suma

    if i had another entry like

    suma
    suma

    then there is no problem.
    Please let me know how to see whether event.result.data is Object or ArrayColllection and assign to Object ot ArrayCollection respectively

  12. Thanks for another great example. Could you shed some light on how to make the images display in a pop-up window like inthe horizontal and the vertical tile-list examples?

    Keep up the great work,
    Larry

  13. Hi..

    How can I read & view an XML file from Adobe FLex…??
    I’m very new to it, PLease do let me know the procedures carried out in it…
    Thanks inAdvance

  14. Hello Peter,

    this post was hint I needed for a problem, I was unable to solve. Thanks for all the Work you put into flexexamples, this is the best resource for Flex ever!

    cheers,
    Norbert

Comments are closed.