简体   繁体   中英

Retrieve data from SQL to display as XML

My SQL query is this

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

Basically it is displaying data as follows:

User         Number of photos uploaded  
Az                   1  
Mz                   3

and so on..

What I want to do is transfer this data to a XML file in the form :

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

or any other appropriate way.

You do the exact same way you would do it if your XML was HTML .

Suppose this is your php script:

<?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>

You did not state your DBMS, but the following will work with PostgreSQL and Oracle:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM