Data Exchange with XML, WDDX and PHP - Money Talks (
Page 8 of 9 )
Let's try another example, this one using WDDX to transmit five-day currency rate data to a requesting client. The client then uses this data to calculate an average rate for the past five days.
Let's assume that the data is stored in the following database table:
mysql> select * from currency;
+--------+-------+-------+-------+-------+-------+
| symbol | mark1 | mark2 | mark3 | mark4 | mark5 |
+--------+-------+-------+-------+-------+-------+
| GBP | 0.72 | 0.69 | 0.73 | 0.75 | 0.69 |
| INR | 0.023 | 0.045 | 0.012 | 0.019 | 0.025 |
| DZD | 0.01 | 0.009 | 0.015 | 0.011 | 0.01 |
| CAD | 0.66 | 0.65 | 0.68 | 0.7 | 0.64 |
| DEM | 0.43 | 0.44 | 0.43 | 0.42 | 0.42 |
+--------+-------+-------+-------+-------+-------+
5 rows in set (0.00 sec)
The server script needs to get all five values and encode them as a WDDX packet.
<?
// server.php - output WDDX packet containing currency data
// database parameters
$hostname = "medusa";
$user = "wddx_agent";
$pass = "jser745mf";
$database = "trends";
// open connection to database
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to
connect!");
// get rates for last five days
$query = "SELECT mark1, mark2, mark3, mark4, mark5 FROM currency WHERE
symbol = '$symbol'";
$result = mysql_db_query($database, $query, $connection) or die ("Error in
query: $query. " . mysql_error());
// add data to packet
if (mysql_num_rows($result) > 0)
{
$mark = mysql_fetch_row($result);
}
mysql_close($connection);
// print packet
echo wddx_serialize_value($mark);
?>
Again, the array of five values is encoded as a WDDX packet, and sent to the requesting client, which decodes it and prints the data, together with an average of all five values.
<?
// client.php - connect to server, retrieve and decode WDDX packet
// url of Web page
$url = "http://medusa/server.php?symbol=$symbol";
// read WDDX packet into string
$package = join ('', file($url));
// deserialize
$rates = wddx_deserialize($package);
?>
<html>
<head>
<basefont face="Verdana">
</head>
<body>
<h3>Five-day currency trends for currency symbol <? echo $symbol; ?></h3>
<table border="1" cellspacing="3" cellpadding="3">
<tr>
<td>Data pointer 1</td>
<td>Data pointer 2</td>
<td>Data pointer 3</td>
<td>Data pointer 4</td>
<td>Data pointer 5</td>
<td>Average</td>
</tr>
<tr>
<?
$sum = 0;
// print rate data
for($x=0; $x<5; $x++)
{
$sum = $sum + $rates[$x];
echo "<td>$rates[$x]</td>";
}
// calculate average
$avg = $sum/5;
echo "<td>$avg</td>";
?>
</tr>
</table>
</body>
</html>
Simple, huh?