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.
<?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.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
23 Responses to Dynamically loading XML files using the HTTPService tag
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


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
I know how to make an XML file using PHP, mail me and i will help you out.
BTW nice article. Helps a lot !! :)
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.
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: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]
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
This is the code i am working on rite now, actually its your code, modified by me ;)
Thanks
<?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><?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>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.
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
Thanks for this! This was exactly what I needed to get my app working.
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?
<?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
?>
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
I got the same problem as Venkat
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
Can you a tutorial on connecting a gallery to picasa or any web albums applications? your examples are really great.
I am having the same problem as sameer. I’m receiving the error he is.
Thanx man this helped me a lot..
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
@ Ashwini
navigate to http://blog.flexexamples.com/2007/08/04/creating-two-related-comboboxes/
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