php - 如何用php修改xml文件
问题描述
我正在尝试在 php 的帮助下更新 XML 文件。我不知道如何使用 php 更新 xml 文件。我创建了两个输入框,在其中我使用表单元素传递值。
<?xml version="1.0" encoding="UTF-8"?>
<inventors>
<person>
<name>anie</name>
<comment>good</comment>
</person>
</inventors>
这是我的php代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<?php
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('sample.xml');
//Get item Element
$element = $xml->getElementsByTagName('person')->item(0);
//Load child elements
$name = $element->getElementsByTagName('name')->item(0);
$comment = $element->getElementsByTagName('comment')->item(0) ;
//Replace old elements with new
$element->replaceChild($name, $name);
$element->replaceChild($comment, $comment);
?>
<?php
if (isset($_POST['submit']))
{
$name->nodeValue = $_POST['namanya'];
$comment->nodeValue = $_POST['commentnya'];
htmlentities($xml->save('ak.xml'));
}
?>
<form method="POST" action=''>
name <input type="text-name" value="<?php echo $name->nodeValue ?>" name="namanya" />
comment <input type="text-comment" value="<?php echo $comment->nodeValue ?>" name="commentnya"/>
<input name="submit" type="submit" />
</form>
</body>
</html>
解决方案
现在你正在尝试混合视图和模型。
您需要指定表单的action
:
<form method="POST" action="person.php">
name <input type="text-name" value="" name="namanya" />
comment <input type="text-comment" value="" name="commentnya"/>
<input name="submit" type="submit" />
在您pearson.php
进行更改时,例如:
if (isset($_POST['submit'])) {
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('sample.xml');
$element = $xml->getElementsByTagName('person')->item(0);
$element->getElementsByTagName('name')->item(0)->nodeValue = $_POST['namanya'];
$element->getElementsByTagName('comment')->item(0)->nodeValue = $_POST['commentnya'];
$xml->save('sample.xml'); // You have ak.xml here, but you wanted to update existing
}
如果您需要一个新文件,请不要替换一些示例 - 只需创建一个新XML
结构。
推荐阅读
- puppet - 如何在 Redhat 中安装 Puppet Enterprise?
- python - 使用格式而不是 f 字符串
- excel - 如何遍历单元格列并写入另一列单元格
- python-3.x - pyspark 将两个数据框与添加的项目/条件合并
- mysql - 如何在 SQL 中查找表中的唯一键
- arrays - 如何使用swift在数组中排列对象属性顺序相同
- c++ - 为什么我的函数不能用字符串的最后一个字符切换第一个字符?
- android - 片段开始时如何将焦点设置为editText?
- ansible - ansible with_sequence 结果消息隐藏
- android - 带有 Pac URI 的 VPN 服务 setHttpProxy