drzb7969753 2017-10-29 08:58
浏览 58
已采纳

尝试使用php simplexml编辑xml文件

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

  $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

  • 写回答

1条回答 默认 最新

  • doudang4857 2017-10-29 09:49
    关注

    Second one is not possible as SimpleXMLElement can only take a well-formed XML string or the path or URL to an XML document. But you are passing an object of class SimpleXMLElement returned by simplexml_load_file. That is the reason it was throwing error 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.

    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.

    So once you have updated your XML with the hints, just save it back to file.

    $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');
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目