开发者

php code to return xml

hi there i have a question and 开发者_StackOverflow社区need help on this from you guys .

I have a database created for a game called gamesleaderboard and the fields are id, player_name, score, leveltime. and my task is after getting the score, i have to insert it to a database and sort the dbase accordingly. after sorting, the code will return an xml in the following structure:

Ahmad100080 Basel95090 Samer920100 Seyd900110 Ahmad100080 Basel95090 Samer920100 Seyd900110 Ahmad100080 Basel95090

plz tell me the necessary details how to do this thankyou.


In most simplistic terms there is nothing really special to do here, you can output XML in exactly the same way you would output HTML in PHP, this is a simple example

You can also use the DOMDocument class (or SimpleXML) to output XML, this is a bit more complex but is better practice. For an example of creating XML with DOMDocument using data from MySQL read more here


Don't forget to send the correct Content-Type header before outputting the XML document tho.


If you are very new to XML I would highly recommend SimpleXML as it will be enough for most of needs. Creating XML using "echo" and strings is not only a dangeous but also a very bad programming technique.

Using SimpleXML you can easily add new nodes, adding child nodes and attributes to them. If you can getting started reading the PHP docs, just search for a SimpleXML tutorial on google. Or ask your questions right here.


$query=mysql_query("Select * from gamesleaderboard ");

$number=mysql_num_rows($query);

if ($query==0)
{
echo "0 rows Affected"; 

}

$doc= new DOMDocument();
$doc->formatOutput=true;

$root= $doc->createElement("Games");
$doc->appendChild($root);

for ($i=0; $i<$number; $i++){

    $row=mysql_fetch_array($qex);

    $node=$doc->createElement("user");
    $pn=$doc->createElement("player_name");
    $pn->appendChild($doc->createTextNode($row["player_name"]));
    $node->appendChild($pn);

    $sc=$doc->createElement("score");
    $sc->appendChild($doc->createTextNode($row["score"]));
    $node->appendChild($sc);

    $root->appendChild($node);
}


echo $doc->saveXML();

This will display the answer exactly you want. I just tested it. I was probably in highschool when you asked this question here. Anyway it'll help someone else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜