gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:36:16 25 4
gpt4 key购买 nike

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

?>

最佳答案

首先,我建议不要使用mysql_* 函数。 They are deprecated and going away .

Dom extension在这种情况下似乎有点矫枉过正。我更喜欢使用 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();

关于php - 如何将 SQL 查询结果转换为 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14144255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com