こんにちは皆さん!
私はかなり大規模なプロジェクトで活動していますが、XMLの経験は限られています。私は動的にXMLを生成しています。これは、個々の顧客のニーズに合わせてカスタマイズできるデータです。現在の解決策は(私を傷つけないでください、私は新しい人です)phpテンプレートをインライン化することinclude()
です。これは良い習慣ではなく、より良い解決策に移行したいと思います。
構造
<?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());
}
これについてどのように進めますか?また、ベストプラクティスは何ですか?少しお腹が空いていて脱水症状なので、基本的なものが足りない場合は教えてください。