【问题标题】:Load, edit and update xml file by html form php通过 html 表单 php 加载、编辑和更新 xml 文件
【发布时间】:2019-11-23 18:11:23
【问题描述】:

我正在尝试编写一个脚本来读取 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());
?>

【问题讨论】:

  • 更好地使用DOMDocument
  • @LarsStegelitz 使用 SimpleXML 没有错。
  • 什么是$node
  • 另外,我不熟悉 SimpleXML 但$sxml 不会包含两个data 元素的数组吗?

标签: php xml forms simplexml


【解决方案1】:

是否要根据 &lt;data&gt; 元素的 name 属性更新 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());

【讨论】:

  • 感谢回复,我需要更改标签内的值(粗体)示例:mytitle]]> 可以这样做吗?不幸的是,xml 文件不是我生成的,我无法更改它。谢谢
  • 您实际上并不需要 CDATA 部分,但无论如何它都有。
  • 脚本可以工作,但在我的服务器上不行,模块没有从模块中传递变量......它可能是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多