Modify xml by php dom

Dear

I would like to use php, dom to modify a xml file. For example, i have a book.xml as below. If I want to change publisher "Thomson" to "Wiley". How can I do that? Does anyone can give me a php code to do this? Thank you very much!

  <books>
  <book>
  <author>Don Gosselin</author>
  <title>PHP Programming with MySQL</title>
  <publisher>Thomson</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  </books>
charles_cpAsked:
Who is Participating?
 
RoonaanCommented:
Using dom you can use the following code. You might want to look into simplexml though for this type of manipulation, or XSLT or SAX.

Kind regards

-r-
<?php
  $str = '<books>
  <book>
  <author>Don Gosselin</author>
  <title>PHP Programming with MySQL</title>
  <publisher>Thomson</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O\'Reilly</publisher>
  </book>
  </books>';
  
  $d = new DomDocument();
  $d->loadXML($str);
  
  $publishers = $d->getElementsByTagName('publisher');
  
  foreach($publishers as $p) {
    if($p->nodeValue == "Thomson") {
      $p->nodeValue = 'Wilson';
    }
  }
  
  
  $newXML = $d->saveXML();
  
  echo '<pre>'.htmlspecialchars($newXML).'</pre>';;
  
?>

Open in new window

0
 
Eddie ShipmanAll-around developerCommented:
Is this PHP4 or PHP5, it makes a difference and is this a file stored somewhere or just in-memory
XML?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.