Welcome Guest, Not a member yet? Register   Sign In
Problem With XML File Accessing
#1

[eluser]WoOzY KinG[/eluser]
So the little application I want to make is to be able to add new entries into and delete from an xml file in a form of such:
Code:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<audio>
    <file>
        <track>http://127.0.0.1/test/cocoweb/1.mp3</track>
        <caption>Coco Music</caption>
        <record>High DJ</record>
    </file>
    <file>
        <track>someother.mp3</track>
        <caption>woot</caption>
        <record>Low DJ</record>
    </file>
</audio>

Entries would be "file" tags. After some docs reading, I had this quick and dirty code working for adding new entries:
Code:
// add
if ( isset($_POST['add']) && isset($_POST['track']) && isset($_POST['caption']) && isset($_POST['record']) ) {
    $file = $xml_src->addChild( 'file' ); // add a new node "file"
    $file->addChild( 'track', $_POST['track'] );
    $file->addChild( 'caption', $_POST['caption'] );
    $file->addChild( 'record', $_POST['record'] );

    if ( $file ) { // if added propery
        $fp = fopen( $source, 'w' );
        fwrite( $fp, $xml_src->asXML() );
        fclose( $fp );
    }
}

And also I've come up with some code to perform the delete job, but it fails:
Code:
// remove - using DOM lib, not finished
if ( $_GET['action'] == 'del' && isset($_GET['del_track']) && isset($_GET['del_caption']) && isset($_GET['del_record']) ) {
    // import from the existing SimpleXML object instead of loading the xml file again
    $node = dom_import_simplexml( $xml_src );
    $dom = new DomDocument();
    $dom->importNode( $node, true );
    $dom->appendChild( $node );

    $del_file = $dom->documentElement;
    $count = 0; // initialize counter

    foreach ( $xml_src as $file ) {
        if ( ($file->track == $_GET['del_track']) && ($file->caption == $_GET['del_caption']) && ($file->record == $_GET['del_record']) ) {
            $del_track = $del_file->getElementsByTagName( 'track' )->item( $count );
            $del_file->removeChild( $del_track );

            $del_caption = $del_file->getElementsByTagName( 'caption' )->item( $count );
            $del_file->removeChild( $del_caption );

            $del_record = $del_file->getElementsByTagName( 'record' )->item( $count );
            $del_file->removeChild( $del_record );

            break; // since we need to delete only one file
        }

        $count++;
    }
    
    //$fp = fopen( $source, 'w' );
    //fwrite( $fp, $dom->DOMNode->saveXML() );
    //fclose( $fp );
}

I hope the code is readable, and just to make it clear, my actual situation here is the delete part. Please gimme a hand Big Grin




Theme © iAndrew 2016 - Forum software by © MyBB