Dynamic XML from a template and hash tree in PHP

edmundblack

New Member
Hello All!I'm active in a fairly large project, but I have limited experience with XML. I am dynamically generating XML, data which may be customed to needs of individual customers. The current solution has been (please don't hurt me, I'm the new guy) to inline a php template by \[code\]include()\[/code\]. This is not good practice and I want to move to a better solution.Structure\[code\]<?xml version='1.0'?><Product id=""> <AswItem></AswItem> <EanCode></EanCode> <ImagePopup></ImagePopup> <ImageInfo></ImageInfo> <ImageThumbnail></ImageThumbnail> <PriceCurrency></PriceCurrency> <PriceValueNoTax></PriceValueNoTax> <Manufacture></Manufacture> <ProductDescriptions> <ProductDescrition language="" id=""> <Name></Name> <Description></Description> <Color></Color> <Size></Size> <NavigationLevel1></NavigationLevel1> <NavigationLevel2></NavigationLevel2> <NavigationLevel3></NavigationLevel3> <NavigationLevel4></NavigationLevel4> </ProductDescrition> </ProductDescriptions> <MatrixProducts> <AswItem></AswItem> <EanCode></EanCode> <ParentId></ParentId> <PriceCurrency></PriceCurrency> <PriceValueNoTax></PriceValueNoTax> <ImagePopup></ImagePopup> <ImageInfo></ImageInfo> <ImageThumbnail></ImageThumbnail> </MatrixProducts></Product>\[/code\]This is our main structure. \[code\]ProductDescriptions\[/code\] and \[code\]MatrixProducts\[/code\] are basically list items, and may contain none to several children. Our object to be translated into XML is a PHP hash tree with a similar structure but with different keys.ProblemThe problem I have is that I get stuck in the thought process on how dynamically create a tree from an object. My current plan is to have a key conversion table (see Current Solution) but a voice in the back of my head is telling me that it's not best practice.Previous solutionpopulate.php\[code\]foreach($products as $product) { // too much black magic in here include($chosenTemplate); // $productXMLString is generated in the previous include printToXML($productXMLString)}\[/code\]template.php\[code\]<? echo "<Product id='{$product['id']}'>";// etc...echo "</product>";\[/code\]As you can see, this is a pretty bad approach. Bad error handling, messy syntax and lot's of other quirks.Current solution\[code\] $xmlProductTemplate = simplexml_load_file($currentTemplate); foreach($products as $product) { $xmlObj = clone $xmlProductTemplate; foreach($product as $key => $productValue) { // if value is a <$key>$string</$key>, just input // it into the translated key for the $xmlObject if(!is_array($productValue)) $xmlObj[translateKeyToXML($key)] = $productValue; // elseway, we need to call the magic; traverse a child array // and still hold true to templateing else { // what DO you do? } }// save xmlfputs($xmlObj->asXML()); }\[/code\]How would you go about this and what is best practice? I'm a bit hungry and dehydrated so please tell me if I'm missing something basic.
 
Back
Top