April 1st, 2007

Save a MySQL query result set to XML

A very cool feature with ASP.Net is that all SQL query result sets are stored locally as XML to be worked on, and then the changes committed to the database. This is very powerful, and I was quit excited to find this new class that enables you to do something similar with PHP.

The class is used to generate XML documents from MySQL query results. Here's a link to the class. How it works is by traversing the result set of an executed SELECT query, and mapping the query results column values into nodes of data of an XML document.

The XML document root node tag, the tag of each result row, and the tags of each result row column are configurable. The resulting XML document is returned as a single string.

Share

One Response to ' Save a MySQL query result set to XML '

Subscribe to comments with RSS or TrackBack to ' Save a MySQL query result set to XML '.


  1. on November 25th, 2008 at 5:29 am

    how about this simple function :)
    just feed it your mysql query object

    function createXML($query)
    {
    if($query->num_rows())
    {
    //convert query results to XML
    $doc = new DomDocument('1.0');
    $root = $doc->createElement('root');
    $root = $doc->appendChild($root);

    foreach ($query->result() as $row)
    {
    $occ = $doc->createElement('learners');
    $occ = $root->appendChild($occ);
    foreach ($row as $fieldname => $fieldvalue)
    {
    $child = $doc->createElement($fieldname);
    $child = $occ->appendChild($child);
    $value = $doc->createTextNode($fieldvalue);
    $value = $child->appendChild($value);
    }
    }
    $xml_string = $doc->saveXML();
    return $xml_string;
    }
    else return -1;
    }

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word