尝试使用 php 简单 xml 编辑 xml 文件

trying to edit xml file using php simplexml

所以我正在尝试使用 php 的简单 xml 扩展来编辑 xml 文件,但我遇到了一些问题及其 当我尝试

  $settings = simplexml_load_file("settings.xml");
  ....
  if(isset($aInformation['cName'])) 
  {
     $settings->general->communityname = $aInformation['cName'];
     $settings->asXML();
  }

但是我保存步骤失败了...

  $settings = simplexml_load_file("settings.xml");
  $xmlconfigs = new SimpleXMLElement($settings); 
  ....
  if(isset($aInformation['cName'])) 
  {
     $settings->general->communityname = $aInformation['cName'];
     $xmlconfigs->asXML();
  }      

但我也失败了

  String couldn't be parsed to XML...

我之前曾尝试搜索这些帖子,但它们与我失败的示例代码相同 edit XML with simpleXML and PHP SimpleXML error update xml file

第二个是不可能的,因为 SimpleXMLElement 只能采用格式正确的 XML 字符串或路径或 URL 到 XML 文档。但是您正在传递 simplexml_load_file 返回的 class SimpleXMLElement 的对象。这就是它抛出错误 String couldn't be parsed to XML...

的原因

在第一个中,asXML() 方法接受一个可选的文件名作为参数,它将当前结构作为 XML 保存到文件中。

If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

因此,一旦您使用提示更新 XML,只需将其保存回文件即可。

$settings = simplexml_load_file("settings.xml");
....
if(isset($aInformation['cName'])) 
 {
   $settings->general->communityname = $aInformation['cName'];
   // Saving the whole modified XML to a new filename
   $settings->asXml('updated_settings.xml');
   // Save only the modified node
   $settings->general->communityname->asXml('settings.xml');
 }