1

基本上,我采用 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;

?>
4

2 回答 2

1

首先,我建议不要使用mysql_*函数。 它们已被弃用并消失

在这种情况下, Dom 扩展似乎是矫枉过正。如果可以,我更喜欢使用SimpleXML

<?php

$dbh = new PDO('mysql:host=localhost;dbname=test','username','password');

$sxe = new SimpleXMLElement('<workResponse></workResponse>');
$sxe_crs = $sxe->addChild('contentResponses');

function array_walk_simplexml(&$value, $key, &$sx) {
    $sx->addChild($key, $value);
}

$stmt = $dbh->query('SELECT * FROM sometable');

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $sx_cr = $sxe_crs->addChild('contentResponse');
    array_walk($row, 'array_walk_simplexml', $sx_cr);
}

echo $sxe->asXML();

如果您想“漂亮地打印” XML(欣赏您的工作?),那么您需要使用 Dom 扩展。

$dom_sxe = dom_import_simplexml($sxe);
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();
于 2013-01-03T20:41:52.220 回答
0

XML_Serializer 对于 php pear 用户非常有用

于 2013-01-03T22:26:16.057 回答