[以html格式php加载,编辑和更新xml文件

问题描述 投票:0回答:1

我正在尝试编写一个脚本来读取XML文件,将其插入表单中,然后使用php编辑和更新值。

表单将加载当前数据,但不会更新它们。

有人可以告诉我小费吗?谢谢毛里齐奥

文件XML

<?xml version="1.0" encoding="UTF-8"?>
<myxml>

  <data name="en_title"><![CDATA[mytitle]]></data>
  <data name="en_scene_title"><![CDATA[ES000021903]]></data>

</myxml>

文件编辑PHP

<?php
$form_fields  = null;
$data = simplexml_load_file('messages_en.xml');
foreach($data->data as $field)
{

  $form_fields .= '<div>';
    $form_fields .=  '<label>' .$field['name'] . ' </label>';
    $form_fields .=  '<input type="text" id="' .$field['name'] . '"placeholder="'.htmlentities($field).'" name="'.$field. '" />';
    $form_fields .= '</div>';
  }
  ?>
  <!DOCTYPE html>
  <html>
  <head>
    <style>
      form { font-size: 16px; }
      form div { margin: .3em; }
      legend { font-weight: bold; font-size: 20px; }
      label { display:inline-block; width: 140px; }
    </style>
  </head>
  <body>
    <form method="POST" action="process.php">
      <legend> Enter Contact Information</legend>
      <?php echo $form_fields; ?>
      <input type="submit" name="submit" value="Upload" class="btn"  />
    </form>
  </body>
  </html>

代码文件process.php

<?php
    $xml = file_get_contents('messages_en.xml');
    $sxml = simplexml_load_string($xml);
    if(isset($sxml->item[$_POST['name']])) {
        $node->data = $_POST['name'];
    }
    file_put_contents('messages_en.xml', $sxml->asXML());
?>
php xml forms simplexml
1个回答
0
投票

是否要基于name元素的<data>属性更新XML?

如果是这样,则需要a)从HTML中传递名称和值,并b)搜索所需的名称。

$var = $_POST["name"];
$val = $_POST["value"];

$xml = file_get_contents("messages_en.xml");
$dom = new DomDocument();
$dom->loadXml($xml);
$xpath = new DomXpath($dom);
// find the data element with the matching attribute
$node = $xpath->query("/myxml/data[@name='$var']");
// assume there's only one, otherwise we can loop
// clear the existing content
$node[0]->textContent = "";
// create a new CDATA section
$node[0]->appendChild($dom->createCDATASection($val));
// save the updated XML
file_put_contents("messages_en.xml", $dom->saveXml());
© www.soinside.com 2019 - 2024. All rights reserved.