Thursday, August 19, 2010

Add a new record in existing XML file

Add a new record in existing XML file



The xml file having the columns as listed below:
ID,author,title,url



full xml file's format is listed below:

blogs.xml
=====================================================
<?xml version="1.0"?>
<blogs>
    <article>
        <ID>1</ID>
      <author>Amit</author>
      <title>Auto Resume Broken Progress Bar File Uploader Applet</title>
      <url>http://amitkgaur.blogspot.com/2010/10/file-upload-applet-with-auto-resume.html</url>
  </article>
    <article>
        <ID>2</ID>
      <author>Amit</author>
      <title>Screen Recorder</title>
      <url>http://amitkgaur.blogspot.com/2010/09/desktop-screen-recorder.html</url>
  </article>
</blogs>
=====================================================


and you want to add a new record(s), then use the listed below my php code.
You need to change it according your requirements.

addNew.php
=====================================================
<?php
$fullXmlFile="blogs.xml";

$ID="3";
$author="Amit Gaur";
$title="How to get clipboard data from webpage.";
$url="http://amitkgaur.blogspot.com/2011/06/how-to-get-clipboard-data-from-webpage.html";

$xmlObj = simplexml_load_file($fullXmlFile);
$sxeObj = new SimpleXMLElement($xmlObj->asXML());
$articleObj = $sxeObj->addChild("article");
$articleObj->addChild("ID", $ID);
$articleObj->addChild("author", $author);
$articleObj->addChild("title", $title);
$articleObj->addChild("url", $url);
$sxeObj->asXML($fullXmlFile);

The above code will add the new record at the last position in the xml file.
=====================================================





2 comments:

  1. hey i've got an error report like this
    parser error : xmlParseEntityRef: no name ...

    can u help me to fix that?

    ReplyDelete
    Replies
    1. Syifa,

      Copy the code and try to run again. now it will
      not show any error.

      Delete