使用php textarea提交在xml文件中更新测试

时间:2011-01-08 01:14:10

标签: php xml dom

需要xml文件的帮助来编辑我的Flash网站的内容,每当我插入textarea例如“name”时它会在xml中创建新的活动,我需要从“游泳”更改为“名称“即可。 我发现要更改xml中的内容我需要删除“游泳”并插入“名称”

如何操作,首先将内容插入textarea - >按“更新”时保存 - >从xml文件中删除旧活动,然后将新内容插入xml文件????

sample.xml中

<?xml version="1.0"?>
<list>
    <activity>swimming</activity>
</list>

的index.php

<html>
<head><title>test</title></head>
</head>

<body>


<table width="100" border="1">
  <tr>
    <td><?php
    $xmldoc = new DOMDocument();
    $xmldoc->load("sample.xml", LIBXML_NOBLANKS);

    $activities = $xmldoc->firstChild->firstChild;
    if($activities!=null){
        while($activities!=null){
            echo $activities->textContent."";
            $activities = $activities->nextSibling;
        }
    }
?></td>
  </tr>
  <tr>
    <td><form name="input" action="insert.php" method="post">

      <textarea name="activity" cols="70" rows="10"><?php
    $xmldoc = new DOMDocument();
    $xmldoc->load("sample.xml", LIBXML_NOBLANKS);

    $activities = $xmldoc->firstChild->firstChild;
    if($activities!=null){
        while($activities!=null){
            echo $activities->textContent."";
            $activities = $activities->nextSibling;
        }
    }
?></textarea>
    </td>
  </tr>
  <tr>
    <td align="right"><input type="submit" value="Update"/>
  <input name="reset" type="reset" id="reset" value="Reset">
</form></td>
  </tr>
</table>

</body>
</html>

insert.php

<?php
    header('Location:index.php');
    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');

    $newAct = $_POST['activity'];

    $root = $xmldoc->firstChild;

    $newElement = $xmldoc->createElement('activity');
    $root->appendChild($newElement);
    $newText = $xmldoc->createTextNode($newAct);
    $newElement->appendChild($newText);

    $xmldoc->save('sample.xml');
?>

谢谢大家的帮助!!!

1 个答案:

答案 0 :(得分:1)

好吧,我自己管理,如果你需要在你的网页上添加或删除内容,只需从顶部复制所有内容,除了insert.php

new insert.php

<?php 
$xmldoc = new DOMDocument;
$xmldoc->load('sample.xml');
foreach ($xmldoc->getElementsByTagName('activity') as $activity)
{
    $activity->parentNode->removeChild($activity);
}
$xmldoc->save('sample.xml');

?>

<?php

    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');

    $newAct = $_POST['activity'];

    $root = $xmldoc->firstChild;

    $newElement = $xmldoc->createElement('activity');
    $root->appendChild($newElement);
    $newText = $xmldoc->createTextNode($newAct);
    $newElement->appendChild($newText);

    $xmldoc->save('sample.xml');

?>

非常感谢