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

    Bookmark the permalink.

    Leave a Reply

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