How to replace particular element's content in xml file using php?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kaushal Elsner
    New Member
    • Jan 2011
    • 23

    How to replace particular element's content in xml file using php?

    Code:
    <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.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    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.

    Comment

    • Kaushal Elsner
      New Member
      • Jan 2011
      • 23

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

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

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

        Comment

        • Kaushal Elsner
          New Member
          • Jan 2011
          • 23

          #5
          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?

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            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.

            Comment

            • Markus Igeland
              New Member
              • Feb 2011
              • 14

              #7
              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

              Comment

              Working...