Datasheet

minute (60 seconds). The second header says that the media type is application/xml. The third
instruction outputs the XML declaration. The tests that follow are to check in which case we are. The first
one checks if data has been posted, in which case you would be handling a request to save a document.
The second one checks if you have received a parameter with a
GET request. This isn’t the case here so
the
listAll function will be executed:
function listAll() {
$db=openDb();
echo “<watches>”;
$query = $db->query(“SELECT * from watches order by symbol”, SQLITE_ASSOC);
while ($row = $query->fetch(SQLITE_ASSOC)) {
displayOne($row);
}
echo “</watches>”;
}
This code starts by calling a function that opens the database. This function has been written so that if
the database doesn’t exist, it is created and if the table that contains the data doesn’t exist, it is also cre-
ated. This insures an auto-install feature for BuzzWatch! The next instruction is to send the
<watches>
start tag that embeds the different records. The SQL query selects all the rows in the table named
watches and orders them by symbols and loops over the rows that are returned by the request and call
the following function for each row:
function displayOne($row) {
$xml = simplexml_load_string(
“<watch><symbol/><tag/><title/><description/></watch>”);
$xml->symbol=$row[‘symbol’];
$xml->tag=$row[‘tag’];
$xml->title=$row[‘title’];
$xml->description=$row[‘description’];
$asXML = $xml->asXML();
print substr($asXML, strpos($asXML, ‘<’, 2));
}
This function uses the handy SimpleXML PHP5 module to populate an XML document. The first
instruction creates an empty document with the structure that needs to be sent, and the next ones assign
values into this document as if the document was a PHP object. The result is then serialized as XML and,
because you want an XML snippet instead of a full XML document, you remove the XML declaration
before sending the snippet.
This is a hack, but a safe one. This hack is needed because BuzzWatch has been developed with PHP
5.1.2. In PHP 5.1.3, new features have been added to SimpleXML that enable you to add nodes to a
document, so the full document could easily be built entirely with SimpleXML and serialized in a
single step.
The result of this script is to send a response, which is:
HTTP/1.1 200 OK
Date: Fri, 21 Jul 2006 10:37:00 GMT
Server: Apache/2.0.55 (Ubuntu) PHP/5.1.2
X-Powered-By: PHP/5.1.2
Cache-Control: max-age=60
14
Chapter 1
04_087889 ch01.qxp 5/2/07 12:56 PM Page 14