1

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

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
Zorono
  • 75
  • 2
  • 12

1 Answers1

0

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');
 }
Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
  • Edit: after some tests again i used `$settings->asXml('settings.xml');` only so it saves the whole settings xml file's content :D thanks so much sir and it works great – Zorono Oct 30 '17 at 07:29