Despite I've checked a lot of StackOverflow questions, as well as Google, I can't find any solution for this. (any solution which I can understand and be able to do).
Source data is in the following tables (depicted as table => columns
)
country_table => id
region_table => id, country_id
city_table => id, region_id
... and so on ...
But when I query&join these tables, they don't share a "master" parent in any way. D'oh!
Code:
function buildLocationTree()
{
//We retrieve raw data from model (Laravelish style)
$aLocations = WhateverModel::getLocations();
$oXML = new SimpleXMLElement('<xml/>');
//I add a root node called 'result'
$oResult = $oXML->addChild('result');
foreach ($aLocations as $oLocation)
{
if (! ($oXML->xpath("//country[@id=" . $oLocation->CountryId . "]")))
{
$oCountry = $oResult->addChild('country', $oLocation->CountryName);
$oCountry->addAttribute('id', $oLocation->CountryId );
}
if (! ($oXML->xpath("//region[@id=" . $oLocation->RegionId. "]")))
{
$oRegion = $oCountry->addChild('region', $oLocation->RegionName);
$oRegion->addAttribute('id', $oLocation->RegionId );
}
//And so on... build many structures 'search in nodes + add child' as deep levels
}
return $oXML;
}
Then do whatever you need with the XML object... jsonize it, build a file...
I'd be nice to have some feedback or listen your thoughts about this solution! Is an acceptable one? Risky or prone to errors?