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
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 returnsTRUE
if the file was written successfully andFALSE
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');
}