首页 > 解决方案 > 如何用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>

标签: php

解决方案


现在你正在尝试混合视图和模型。

您需要指定表单的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结构。


推荐阅读