Wednesday, 19 August 2009

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"?>
    <music>
    <newItemID>
    <titleID>very soon.mp3</titleID>
    <urlID>http://www.filerecycle/music/very soon.mp3</urlID>
    <dateID>9/8/2009</dateID>
    <descriptionID>delete fodder...</descriptionID>
    </newItemID>
    <newItemID id="2625">
    <titleID>id.mp3</titleID>
    <urlID>http://www.filerecycle/music/id.mp3</urlID>
    <dateID>10/8/2009</dateID>
    <descriptionID>song?</descriptionID>
    </newItemID>
    </music>



  • 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"/>

  • 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>
    </mx:request>
    </mx:HTTPService>



  • 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());
    ?>

    No comments: