[英]Dynamic XML from a template and hash tree in PHP
我在一个相当大的项目中很活跃,但是我对XML的经验有限。 我正在动态生成XML,这些数据可以根据单个客户的需求进行定制。 当前的解决方案是(请别伤害我,我是新手)通过include()
内联php模板。 这不是一个好习惯,我想寻求一个更好的解决方案。
<?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>
这是我们的主要结构。 ProductDescriptions
和MatrixProducts
基本上是列表项,可能不包含几个子项。 我们要转换为XML的对象是具有相似结构但具有不同键的PHP哈希树。
我的问题是,我陷入了如何从对象动态创建树的思考过程中。 我目前的计划是要有一个密钥转换表(请参阅“当前解决方案”),但是我脑海中回荡着声音告诉我这不是最佳实践。
populate.php
foreach($products as $product) {
// too much black magic in here
include($chosenTemplate);
// $productXMLString is generated in the previous include
printToXML($productXMLString)
}
template.php
<?
echo "<Product id='{$product['id']}'>";
// etc...
echo "</product>";
如您所见,这是一个非常糟糕的方法。 错误的错误处理,凌乱的语法以及许多其他怪癖。
$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 xml
fputs($xmlObj->asXML());
}
您将如何处理?什么是最佳做法? 我有点饿且脱水,所以请告诉我是否缺少基本的东西。
我在理解您要尝试执行的操作时遇到了一些麻烦,请原谅。 您似乎想要做的事情是基于带有包含XML元素的属性和值的ArrayObject的“模板”创建XML文件。
也许,您只是创建一个SimpleXML对象,而不是尝试这样做。 我认为这样做对您来说要容易得多,它增加了错误捕获的价值。 请参阅PHP.net上的SimpleXML 。
如果我的答案不正确,是否可以发布更多源代码,例如包含值的类? 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.