Write in XML using PHP

Discussion in 'PHP' started by emi87, Dec 15, 2008.

  1. #1
    Hello,
    I have a file test.xml and it looks like this:
    <?xml version="1.0"?>
    <xml>
      <track>
        <path>records/[COLOR="Red"]artist[/COLOR]/record1.mp3</path>
        <title>track01</title>
      </track>
    </xml>
    PHP:
    I want using a php script to be able to add a new record to the xml file. Artist is a php variable that I`ll use in the php script. After adding for example record2.mp3 I want the .xml file to look like this:
    <?xml version="1.0"?>
    <xml>
      <track>
        <path>records/artist/record1.mp3</path>
        <title>track01</title>
      </track>
      <track>
        <path>records/artist/record2.mp3</path>
        <title>track01</title>
      </track>
    </xml>
    PHP:
    and to be saved.

    Thank you!
     
    emi87, Dec 15, 2008 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    Easiest way (without using bulky XML handling features): I didn't fully understand your stuff about artists, but I'm pretty sure anyone could tweak this to how they need it.

    <?php
    
    define( 'FILE', 'f.xml' );
    
    function addTrack( $path, $title = '' )
    {
        $file = file_get_contents( FILE );
        $file = str_replace('</xml>', $add = "\t<track>\n\t\t<path>$path</path>\n\t\t<title>$title</title>\n\t</track>\n</xml>", $file);
        file_put_contents(FILE, $file);
    }
    
    addTrack('path', 'title');
    PHP:
    Uses tabs to indent lines.
     
    Danltn, Dec 15, 2008 IP
  3. emi87

    emi87 Peon

    Messages:
    49
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This is what I want !!!

    THANK YOU VERY MUCH Danltn!!!!
    :* :* :* :*
     
    emi87, Dec 15, 2008 IP