从SQL检索数据以显示为XML

时间:2011-11-13 10:43:10

标签: php sql xml

我的SQL查询是这个

  SELECT firstname AS 'User', count( * ) AS 'Number of photos uploaded'
    FROM members
    JOIN member_photo
   USING ( member_id )
GROUP BY firstname

基本上它显示的数据如下:

User         Number of photos uploaded  
Az                   1  
Mz                   3

依旧......

我想要做的是将这些数据传输到以下格式的XML文件:

<photos>
    <user>Az</user>
    <user_photos>1</user_photos>
    <user>Mz</user>
    <user_photos>3</user_photos>
</photos>

或任何其他适当的方式。

2 个答案:

答案 0 :(得分:1)

如果您的 XML HTML ,则执行相同的操作。

假设这是您的 php 脚本:

<?php
header('Content-Type: text/xml')'
?>
<photos>
<?php
$query = "select ... form foo...";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
?>
    <user><?= $row['user'] ?></user>
    <user_photos><?= $row['photos_count'] ?></user_photos>
<?php
}
?>
</photos>

答案 1 :(得分:0)

您没有说明您的DBMS,但以下内容适用于PostgreSQL和Oracle:

SELECT '<photos>'||xmlforest(firstname AS "user", count( * ) AS user_photos)||'</photos>'
FROM members
  JOIN member_photo USING ( member_id )
GROUP BY firstname