How to replace particular element’s content in xml file using php? – PHP

  php

Q(Question):


<main_xml>
<tag1>
<![CDATA[
<div id=1>
Hello
</div>
<div id=2>
Hi
</div>
]]>
</tag1>
</main_xml>

I want to change Hi to How are You? What should be done. I want code for this replacement. Thanks in advance.

A(Answer):

there are two possible ways.
– get the CDATA text and use str_replace()
– get the CDATA text, render it anew as XML, replace the textContent via DOM, import the output of the 2nd XML into the 1st XML

important: a CDATA section is its own node type and everything contained is text.

A(Answer):

Thanks very much for your reply but if you provide coding for that, then it would be much easier to me.

A(Answer):

practically the same as in your other threads about this XML.

A(Answer):

ok. Now can you tell me how to use getElementsById to identify a perticular tag & to echo that div’s content. A small example please… Based on my xml file(I want to echo Hi based on id=2). In this how we can use getElementsById function?

A(Answer):

if I remember right you have to either parse that XML chunk as HTML or parse it with a DTD that defines id as ID type attribute.

A(Answer):

You should read up on the PHP-class called SimpleXML. It’s not really simple, but easier to understand and work with than creating your own way to parse your XML-files. http://php.net/manual/en/book.simplexml.php

LEAVE A COMMENT