PHP Code

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

1 Comments

  1. 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

Your email address will not be published. Required fields are marked *

*
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.
Anti-spam image