trouble with php/xml edit via form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • akristof
    New Member
    • Nov 2011
    • 25

    trouble with php/xml edit via form

    Hello
    I am trying to use php to add nodes to an xml file based on user input
    The problem is that the xml ends up having data inserted into it in addition to the data I asked the php to insert

    Here are the codes:

    for SAMPLE.XML
    Code:
    <?xml version="1.0"?>
    <list>
        <activity><name>swimming</name><votes>2</votes></activity>
        <activity><name>running</name><votes>3</votes></activity>
        <activity><name>Jogging</name><votes>4</votes></activity>
    </list>
    for INSERT.PHP
    Code:
    <?php
        header('Location:index.php');
        $xmldoc = new DOMDocument();
        $xmldoc->load('sample.xml');
    
        $newAct = $_POST['activity'];
    
    $xmldoc->formatOutput = true;
    
        $root = $xmldoc->firstChild;
        $newActivity = $xmldoc->createElement('activity');
        $root->appendChild($newActivity);
    
        $newActName = $xmldoc->createElement('name');
        $newActText = $xmldoc->createTextNode($newAct);
        $newActName->appendChild($newActText);
        $newActivity->appendChild($newActName);
    
        $newActVote = $xmldoc->createElement('votes');
        $newActVoteCount = $xmldoc->createTextNode('1');
        $newActVote->appendChild($newActVoteCount);
        $newActivity->appendChild($newActVote);
    
        $xmldoc->save('sample.xml');
    ?>
    for INDEX.PHP
    Code:
    <html>
    <head><title>test</title></head>
    </head>
    
    <form name="input" action="insert.php" method="post">
        insert activity:
        <input type="text" name="activity"/>
        <input type="submit" value="send"/>
    </form>
    
    <?php
        $xmldoc = new DOMDocument();
        $xmldoc->load("sample.xml", LIBXML_NOBLANKS);
    
    $activitylist = $xmldoc->getElementsByTagName( "activity" );
    foreach( $activitylist as $activity )
    {
      $actname = $activity->getElementsByTagName( "name" );
      $name = $actname->item(0)->nodeValue;
      
      $votecount = $activity->getElementsByTagName( "votes" );
      $votes = $votecount->item(0)->nodeValue;
     
      echo "<b>$name ----- $votes votes</b><br>";
    }
    ?>
    </body>
    </html>
    please help! I am losing my mind here!!
  • akristof
    New Member
    • Nov 2011
    • 25

    #2
    here's what ends up being displayed in index.php.. the last line with
    "----- 1 votes" is the redundant stuff .. no idea how it got there!!

    swimming ----- 2 votes
    running ----- 3 votes
    Jogging ----- 4 votes
    swimming ----- 1 votes
    ----- 1 votes

    Comment

    Working...