Monday, October 4, 2010

Converting data to xml

In the weekend I tried a small php prog to convert MySql data to xml. Each field (column) name is created as a tag while each field value is put between these tags. First a connection and a query are run against a small table which has users' id, name and password (3 columns).

            initDB();  // opens and connects to Test db
            $table_id = 'user';
            $query = "SELECT * FROM $table_id";
            $dbresult = mysql_query($query);

Then a document object with the root element (testroot) is created;
       $doc = new DOMDocument('1.0', 'UTF-8');
       $root = $doc->createElement('testroot');
       $root = $doc->appendChild($root);

Then for each record (row) in the table the table name is used as an element under the root. For testing I added two attributes to this element;
            while($row = mysql_fetch_assoc($dbresult)) {
                $occ = $doc->createElement($table_id);
                $occ = $root->appendChild($occ);
                $occ->setAttribute('att1', 'val1');
                $occ->setAttribute('att2', 'val2');

Then for each field (column) in the row ($row array) each name/value pair are added as elements (tags) and values (between the tags);
                foreach ($row as $fName => $fVal) {
                    $child = $doc->createElement($fName);
                    $child = $occ->appendChild($child);
                    $value = $doc->createTextNode($fVal);
                    $value = $child->appendChild($value);
                } // foreach
            } // while

The doc object is then put into an xml string, saved as an xml file (TestTony.xml) and displayed on screen;
            $xml_string = $doc->saveXML();
            $doc->save("TestTony.xml");
            echo $xml_string;

Note that in IE8 the tags can only be seen if viewsource is used. However if you open the xml file you see this;
<?xml version="1.0" encoding="UTF-8" ?>
 <testroot>
 <user att1="val1" att2="val2">
  <id>TM</id>
  <name>Tony Montanaro</name>
  <password>1234</password> 
 </user>
 <user att1="val1" att2="val2">
  <id>TT</id>
  <name>Test User</name>
  <password>*A4B6157319038724E3560894F7F932C8886EBFCF</password>
 </user>
 <user att1="val1" att2="val2">
  <id>TO</id>
  <name>Tony</name>
  <password>1234</password>
 </user>
<user att1="val1" att2="val2">
  <id>MM</id>
  <name>Mario</name>
  <password>4567</password>
 </user>
 <user att1="val1" att2="val2">
  <id>VIC</id>
  <name>Victor</name>
  <password>VCC</password> 
 </user>
 <user att1="val1" att2="val2">
  <id>JOE</id>
  <name>Joe</name>
  <password>JJJ</password>
  </user>
 <user att1="val1" att2="val2">
  <id>CCC</id>
  <name>Carmen</name>
  <password>CCC</password> 
 </user>
 </testroot>

No comments:

Post a Comment