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

报告相同问题?