preload

How to add data to an XML file in PHP

Manipulating XML files is not something all developers deal with on a daily basis, but it is something that must be done. This series of posts will each showcase the most popular XML manipulation techniques that a developer should know. In this entry you will learn how to add elements and text to an XML file from PHP.

Our XML File

Here is our XML file.

We are going to insert a new <Link> child element that holds sibling elements <title> and <url>.

<?xml version="1.0" encoding="ISO-8859-1"?>
<MyLinksCentral>
    <Links>
        <Link>
            <title>Krio Media</title>
            <url>http://www.krio.me</url>
        </Link>
        <Link>
            <title>SEO Miami</title>
            <url>http://www.mercadeoporinternet.com/</url>
        </Link>
    </Links>
</MyLinksCentral>

How To Add The XML Elements

And here is how we add the new elemnts to the document

  $xdoc = new DomDocument;
  $xdoc->Load('MyLinksCentral.xml');

        $links = $xdoc->getElementsByTagName('Links')->item(0);
        $newLinkElement = $xdoc ->createElement('Link');
        $newTitleElement = $xdoc ->createElement('title');
        $newURLElement = $xdoc ->createElement('url');

        $urlNode = $xdoc ->createTextNode ('Google');
        $titleNode = $xdoc ->createTextNode ('http://www.google.com');

        $newTitleElement -> appendChild($titleNode);
        $newURLElement -> appendChild($urlNode);

        $newLinkElement -> appendChild($newTitleElement);
        $newLinkElement -> appendChild($newURLElement);

        $links -> appendChild($newLinkElement);

$xdoc->save('MyLinksCentral.xml');

Step-By-Step Analysis Of The XML

Load – We load the XML file.

getElementsByTagName – We get the Links element, which holds all of our links.

createElement – We create the elements that we will be inserting into our XML file and save them into a variable.

createTextNode – We place the values of the elements into variables. In this case it is the URL and Title we want. We we will inserting Google as the Title and http://google.com as the URL.

appendChild – We put the text we just created into the actual elements <title> and <url>.

appendChild – The next set of appendChild’s are to place the complete <title> and <url> tags inside of our <Link> element.

The final appendChild is to insert the final <Link> tag into the <Links> element of the XML file to be saved.

Leave a Reply

* Required
** Your Email is never shared