
There are two tables, which have a relationship(one-to-many). There are Meals table which contains values such as Breakfast(id: 1), Brunch(id: 2), Lunch(id: 3), Tea(id: 4), Dinner(id: 5) and Supper(id: 6). Then there are Foods table which contains various foods and each food(i.e. Hamburger) is linked to a particular type of meal(i.e. Lunch) via a foreign key. So, the row idfood: 12; idmeal: 3; foodname: "Hamburger" would mean that "Hamburger" is of Lunch meal type.
I created an XML generator file which pulls the contents of the whole Food table into an XML file. Problem is I want to translate idmeal foreign key values into actual meal names from the Meal table for each food element inside XML.
The simple way would be to include the foreign key number from Food table, but that would be too cryptic(i.e. Hamburger is eaten during 3 time). Instead I wanted to make it so based on whatever the foreign key number is – the XML would insert the right value from the Meals tables(mealname) into that one XML file with foods so that I could print something like “Hamburger is eaten during Lunch time”.
GenerateXML.php:
<?php
require("includes/credentials.php");
$doc = new DOMDocument("1.0");
$node = $doc->createElement("foods");
$parnode = $doc->appendChild($node);
$connection=mysql_connect($host, $usr, $pass);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM food";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
while ($row = @mysql_fetch_assoc($result)){
$node = $doc->createElement("food");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("idfood", $row['idfood']);
$newnode->setAttribute("idmeal", $row['idmeal']);
$newnode->setAttribute("foodname", $row['foodname']);
}
echo $xmlfile = $doc->saveXML();
?>
join the tables in your query to make use of your FK relationship.