简体   繁体   English

尝试使用php simplexml编辑xml文件

[英]trying to edit xml file using php simplexml

so I am trying to edit an xml file using php's simplexml extension but I am getting some problems and its when I tried 所以我试图使用php的simplexml扩展名来编辑xml文件,但是当我尝试使用xml文件时却遇到了一些问题

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

but I failed with the saving step... 但是我在保存步骤上失败了...

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

but I failed too with the error 但我也因错误而失败

  String couldn't be parsed to XML...

and I had tried searching on those posts before but they are the same as my failed example codes something edit XML with simpleXML and PHP SimpleXML error update xml file 并且我之前曾尝试搜索这些帖子,但它们与我的失败示例代码相同,即使用simpleXMLPHP 编辑XML的东西SimpleXML错误更新xml文件

Second one is not possible as SimpleXMLElement can only take a well-formed XML string or the path or URL to an XML document. 第二个是不可能的,因为SimpleXMLElement只能采用格式正确的XML字符串或XML文档的路径或URL。 But you are passing an object of class SimpleXMLElement returned by simplexml_load_file . 但是,您正在传递由simplexml_load_file返回的类SimpleXMLElement的对象。 That is the reason it was throwing error String couldn't be parsed to XML... 这就是它抛出错误String couldn't be parsed to XML...

In first one the asXML() method accepts an optional filename as parameter that will save the current structure as XML to a file. 在第一个中, asXML()方法接受一个可选的文件名作为参数,该参数会将当前结构作为XML保存到文件中。

If the filename isn't specified, this function returns a string on success and FALSE on error. 如果未指定文件名,则此函数在成功时返回字符串,而在错误时返回FALSE If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise. 如果指定了参数,则如果文件已成功写入,则返回TRUE ,否则返回FALSE

So once you have updated your XML with the hints, just save it back to file. 因此,使用提示更新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');
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM