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!

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *