Modify xml by php dom

Posted on 2007-10-03
Medium Priority
Last Modified: 2008-09-22

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!

  <author>Don Gosselin</author>
  <title>PHP Programming with MySQL</title>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
Question by:charles_cp
LVL 26

Expert Comment

by:Eddie Shipman
ID: 20049929
Is this PHP4 or PHP5, it makes a difference and is this a file stored somewhere or just in-memory
LVL 49

Accepted Solution

Roonaan earned 500 total points
ID: 20955974
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

  $str = '<books>
  <author>Don Gosselin</author>
  <title>PHP Programming with MySQL</title>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  $d = new DomDocument();
  $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


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month16 days, 7 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question