Created
March 26, 2012 06:08
-
-
Save emayk/2203351 to your computer and use it in GitHub Desktop.
php : sql2xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @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 below line. | |
*/ | |
// header("Content-Type: application/xml"); | |
// echo sqlToXml($result, "companies", "company"); | |
// result : | |
// <?xml version="1.0" encoding="ISO-8859-1" ?> | |
<!-- <companies> --> | |
<!-- <company> --> | |
<!-- <id>1</id> --> | |
<!-- <companyid>1</companyid> --> | |
<!-- <name>microsoft</name> --> | |
<!-- </company> --> | |
<!-- . --> | |
<!-- . --> | |
<!-- . --> | |
<!-- </companies> --> | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment