我希望peter元素替换为其他元素I Input It。我尝试使用replace()
但它不起作用。我不知道我的代码是对还是错。
我希望有人来解决我的问题.Thx
这是XML代码:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<information>
<name>peter</name>
</information>
</document>
这是PHP代码:
<html>
<head>
</head>
<body>
<form action="index.php" method="POST">
Name:<input type="text" name="name"/><br/>
<input type="submit" name="ok" value="add" /><br>
<input type="submit" name="check" formaction="read.php" value="check the date" />
</form>
<?php
if(isset($_POST['ok'])){
$xml= new DomDocument("1.0","UTF-8");
$xml->load("write.xml");
$rootTag=$xml->getElementsByTagName("document")->item(0);
$dataTag=$xml->createElement("information");
$NameTag= $xml->createElement("name",$_POST['name']);
$dataTag->appendChild($NameTag);
$rootTag->appendChild($dataTag);
$dataTag->replaceChild($NameTag,$NameTag);
$xml->formatOutput = true;
$string_value=$xml->saveXML();
$xml->save("write.xml");
}
?>
</body>
</html>
答案 0 :(得分:0)
我认为可能的解决方案是找到当前的name元素,创建一个新的name元素,然后使用replaceChild将当前name元素替换为新的name元素:
例如:
<html>
<head>
</head>
<body>
<form action="index.php" method="POST">
Name:<input type="text" name="name"/><br/>
<input type="submit" name="ok" value="add"/><br>
<input type="submit" name="check" formaction="read.php" value="check the date"/>
</form>
<?php
if (isset($_POST['ok'])) {
$xml = new DomDocument("1.0", "UTF-8");
$xml->load("write.xml");
$currentNameElement = $xml->getElementsByTagName('information')->item(0)->getElementsByTagName('name')->item(0);
$newNameElement = $xml->createElement("name", $_POST['name']);
$currentNameElement->parentNode->replaceChild($newNameElement, $currentNameElement);
$xml->formatOutput = true;
$string_value = $xml->saveXML();
$xml->save("write.xml");
}
?>
</body>
</html>