How to Replace a Child Node with a New Child Node in an XML
Document using PHP
programming in PHP there might be a need to replace some characters in a string
to some other characters. Under such circumstances the replaceData function is
used. This function is used to replace characters from a TextNode. The TextNode
would be of type DOMCharacterData.
function replaceData takes three parameters as inputs. First one is the offset,
the second one is the count and the third one is the string that is to be used
for replacement. The first parameter is the offset that serves as the starting
point for the replacement to take place. The count gives the number of characters
that is to be replaced and the third is the string that is used for replacement.
If the offset or the count is negative this function throws a DOMException.
the XML file candidate.xml given below:
the above file we would create a new element called candidatedesignation and then
create a TextNode with the text "Project Manager". Then we will replace
the word "Project" as "General" using the replaceData function.
The code for the above task is given below:
= new DomDocument;
//You can replace the path to your xml file in the next
line of code.
$newElement = $xdoc
$txtNode = $xdoc ->createTextNode
$candidate -> appendChild($newElement);
the file to any name of your choice.
$test = $xdoc->save("C:/php/xml_files/candidate2.xml");
above code in PHP creates a new element name candidatedesignation and then creates
a TextNode with the text "Project Manager". Then the replaceData function
in PHP replaces the data "Project" as "General". We append
this new element to the xml file and then save it in the name of candidate2.xml.
execution of this code, you can open the file candidate2.xml. The content of that
file would be something like given hereunder:
we can use the replaceData function in PHP to replace data in a textNode while
working on an XML file.
Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.
: We never rent, trade, or sell my email lists to
We assure that your privacy is respected