如何将SQL查询的结果转换为XML?

时间:2013-01-03 17:43:13

标签: php mysql xml dom foreach

基本上,我正在进行SQL查询并将其转换为动态XML。我正在尝试为从查询中获取的元素创建自定义XML标记,并且我想选择将查询中的哪些结果用作XML元素。

在一个完美的世界中,我希望能够从查询中获取每一行并确定XML属性。我希望这是一个循环,但我似乎无法让它工作。

$sql = "SELECT 
COUNT( l.log_id ) AS id, 
l.status AS 'requestStatus',
d.firmname AS 'name',
DAY (FROM_UNIXTIME( l.time ) ) AS DAY, 
WEEK( FROM_UNIXTIME( l.time ) ) AS week, 
YEAR( FROM_UNIXTIME( l.time ) ) AS year

FROM $table_id1, $table_id2 
WHERE 
l.client = 'XXXXX' AND 
l.time > 1 AND 
l.work_id = d.subid AND 
d.deleted = 0 AND
d.user_id = l.user_id

GROUP BY 
YEAR( FROM_UNIXTIME( l.time ) ), 
WEEK( FROM_UNIXTIME( l.time ) ) 

ORDER BY 
week DESC";

$dbresult = mysql_query($sql);

// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$doc->formatOutput = true;

// create root node
$root = $doc->createElement('workResponse');
$root = $doc->appendChild($root);
$occ2 = $doc->createElement('contentResponses');
$occ2 = $root->appendChild($occ2);


// process one row at a time
while($row = mysql_fetch_assoc($dbresult)) {

// add node for each row
$occ = $doc->createElement("contentResponse");
$occ = $root->appendChild($occ);


// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
  $child = $doc->createElement($fieldname);
  $child = $occ->appendChild($child);
    $value = $doc->createTextNode($fieldvalue);
    $value = $child->appendChild($value);

    } // foreach

}// while

// get completed xml document
$xml_string = $doc->saveXML();

echo $xml_string;

?>

0 个答案:

没有答案