Modify xml by php dom

Posted on 2007-10-03
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

    Is this PHP4 or PHP5, it makes a difference and is this a file stored somewhere or just in-memory
    LVL 49

    Accepted Solution

    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


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    794 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

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now