PHPBuilder - mysql2xml class



RSS Twitter
Snippets Databases

mysql2xml class

by: chris alsop
|
April 19, 2001

Version: 1.0.0

Type: Class

Category: Databases

License: GNU General Public License

Description: this is nothing major but i needed to convert a mysql resultset to xml so here is the class. it is basic but use as you wish.



<? ## name:		/common/mysql2xml.php
   ## desc:		converts mysql resultset to an xml doc.
   ## written by:	chris alsop - chris@mindpointe.com
   ## created on:	04-19-2001
   ## last modified:	04-19-2001	chris alsop	- initial coding
   ## notes:            returns the string "EMPTY" if no resultset
   ## ******************************************************************


     // SAMPLE USAGE:
     // $sSql = "SELECT * FROM user";
     // First Arg is the database and the 2nd is the sql query
     // $oXml = new mysql2xml("mysql",$sSql);
     // $x    = $oXml->getXml();

     // echo $x;


      class mysql2xml {
         var $sHost = "YOUR_HOSTNAME";
         var $sUser = "YOUR_USERNAME";
         var $sPass = "YOUR_PASSWORD";
         var $sDb;
         var $sSql;

         function mysql2xml($sDb,$sSql) {
            $this->sDb  = $sDb;
            $this->sSql = $sSql;
         }

         function connect() {
            mysql_connect($this->sHost,$this->sUser,$this->sPass);
            mysql_select_db($this->sDb);
         }

         function getXml() {
            $this->connect();
            $iRes = mysql_query($this->sSql);
            if(!mysql_num_rows($iRes)) {
               return "EMPTY";
            } else {
               $iNumFields  = mysql_num_fields($iRes);
               $iNumRes     = mysql_num_rows($iRes);

               $sRet        = "<?xml version=\"1.0\"?>\n";
               $sRet       .= "<RESULTSET COUNT=\"$iNumRes\">\n";

               while($iRow = mysql_fetch_array($iRes)) {
                  $sRet    .= "   <RESULT>\n";
                  
                  for($a = 0; $a < $iNumFields; $a++) {
                     $sTmp  = mysql_field_name($iRes,$a);
                     $sRet .= "      ".strtoupper("<$sTmp>");
                     $sRet .= $iRow["$sTmp"];
                     $sRet .= strtoupper("</$sTmp>")."\n";
                  }

                  $sRet    .= "   </RESULT>\n";
               }

               $sRet       .= "</RESULTSET>\n";

               return $sRet;
            }
         }
     }
?>

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
chris alsop

Comment:



Comment:

(Maximum characters: 1200). You have characters left.