I have a PHP Script that connects to a database, fetches results and presents them as an XML file.
<?php
header('Content-type: text/xml');
mysql_connect('host','user','password');
mysql_select_db('a8273293_blogger');
$sql = "Select * from Messages";
$q = mysql_query($sql) or die(mysql_error());
$result = mysql_query("SELECT COUNT(id) AS total FROM Messages"); // Query to count IDs
$data = mysql_fetch_assoc($result); // Fetch query result
$countNo = $data['total']; // Store count value in var $countNo
$dom = new DOMDocument();
$root = $dom->createElement('root'); // Root element
$dom->appendChild($root);
while($r = mysql_fetch_array($q)){
$user = $dom->createElement('username'); // Define tag name
$userContent = $dom->createTextNode($r['user_username']); // Field
$user->appendChild($userContent); // Add content to tag
$text = $dom->createElement('text');
$textContent = $dom->createTextNode($r['text']);
$text->appendChild($textContent);
$posted_at = $dom->createElement('posted_at');
$posted_atContent = $dom->createTextNode($r['posted_at']);
$posted_at->appendChild($posted_atContent);
$messages = $dom->createElement('messages'); // Container
$messages->appendChild($user); // Add field
$messages->appendChild($text);
$messages->appendChild($posted_at);
// Count
$count = $dom->createElement('result'); // Define tag name
$countContent = $dom->createTextNode($countNo); // Field
$count->appendChild($countContent); // Add content to tag
$root->appendChild($count); // Add blah
$root->appendChild($messages); // Add content to root
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
This script creates an XML document which is all good but after the script is finished can i convert the file to XML? This is because I want to attach a Cron Job so that information can be gathered again after each day... This will eventually be used to feed information to an app.
Also is it better to try and concatenate or just create a new row with all the data I need in it?
For example if I had firstname, surname, title and I wanted everything from these 3 as one string in an XML tag as a pose to three could I just merge them?
Also if I only wanted my count function to output once could I place it outside of the while loop?
I appreciate this question is rather verbose but I am unsure about particular parts.