Welcome, guest | Sign In | My Account | Store | Cart

Converting MySQL queries to XML

PHP, 50 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * @param mysql_resource - $queryResult - mysql query result
 * @param string - $rootElementName - root element name
 * @param string - $childElementName - child element name
 */
function sqlToXml($queryResult, $rootElementName, $childElementName)
{ 
    $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; 
    $xmlData .= "<" . $rootElementName . ">";
 
    while($record = mysql_fetch_object($queryResult))
    { 
        /* Create the first child element */
        $xmlData .= "<" . $childElementName . ">";
 
        for ($i = 0; $i < mysql_num_fields($queryResult); $i++)
        { 
            $fieldName = mysql_field_name($queryResult, $i); 
 
            /* The child will take the name of the table column */
            $xmlData .= "<" . $fieldName . ">";
 
            /* We set empty columns with NULL, or you could set 
                it to '0' or a blank. */
            if(!empty($record->$fieldName))
                $xmlData .= $record->$fieldName; 
            else
                $xmlData .= "null"; 
 
            $xmlData .= "</" . $fieldName . ">"; 
        } 
        $xmlData .= "</" . $childElementName . ">"; 
    } 
    $xmlData .= "</" . $rootElementName . ">"; 
 
    return $xmlData; 
}


USAGE :


/* Sql query */
$result = mysql_query("SELECT * from company");
 
/* If you want to process the returned xml rather than send it
    to the browser, remove the following line.
*/
header("Content-Type: application/xml");
echo sqlToXml($result, "companies", "company");

1 comment

Xavier L. 12 years, 3 months ago  # | flag

I would consider using an array instead of an object. It would reduce the amount of code needed and would probably be faster.

Created by sameer borate on Thu, 11 Sep 2008 (MIT)
PHP recipes (51)
sameer borate's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks