から、私は次のような配列があります。再帰のDOMDocument PHP配列
Array
(
[0] => Array
(
[name] => Residential
[attributes] => Array
(
[Type] => Townhouse
)
)
[1] => Array
(
[name] => Value
[value] => 250000
)
[2] => Array
(
[name] => Other
[value] =>
)
[3] => Array
(
[name] => Price
[attributes] => Array
(
[PriceAmount] => 200000
[Contract] => No
[StampDuty] => 20000
)
[0] => Array
(
[name] => Date
[value] => 2015-09-16
)
)
[4] => Array
(
[name] => Income
[attributes] => Array
(
[RentalAmount] => 2000
)
[0] => Array
(
[name] => Period
[attributes] => Array
(
[Unit] => Monthly
)
)
)
[5] => Array
(
[name] => Contact
[attributes] => Array
(
[Type] => Owner
)
[0] => Array
(
[name] => Company
[attributes] => Array
(
[Business] => ABC Contacts
)
)
[1] => Array
(
[0] => Array
(
[name] => Person
[0] => Array
(
[name] => Title
[attributes] => Array
(
[Value] => Mr
)
)
[1] => Array
(
[name] => First
[value] => Michael
)
[2] => Array
(
[name] => Surname
[value] => Jordan
)
)
)
[2] => Array
(
[name] => Home
[0] => Array
(
[name] => Phone
[0] => Array
(
[name] => Mobile
[value] => 0414888999
)
)
[1] => Array
(
[name] => Phone
[0] => Array
(
[name] => Fixed
[attributes] => Array
(
[CountryCode] =>
[AreaCode] =>
)
[value] => 99999999
)
)
)
)
)
を私はXMLでその配列を取得するために、DOMを生成しようとする再帰関数を使用しています:
private function GenerateElements($dom, $data)
{
$child = '';
if (empty($data['name'])) {
if (is_array($data)) {
foreach ($data as $item) {
$child = $this->GenerateElements($dom, $item);
}
}
return $child;
}
// Create the element
$element_value = (!empty($data['value'])) ? $data['value'] : null;
$element = $dom->createElement("ns5:" . $data['name'], $element_value);
// Add attributes
if (!empty($data['attributes']) && is_array($data['attributes'])) {
foreach ($data['attributes'] as $attribute_key => $attribute_value) {
$element->setAttribute($attribute_key, $attribute_value);
}
}
// Any other items in the data array should be child elements
foreach ($data as $data_key => $child_data) {
if (!is_numeric($data_key)) {
continue;
}
$child = $this->GenerateElements($dom, $child_data);
if ($child) {
$element->appendChild($child);
}
}
return $element;
}
$doc = new DOMDocument();
$child = $this->GenerateElements($doc, $arr);
if ($child)
$doc->appendChild($child);
$xml = $doc->saveXML();
私がいる問題は、コードが各要素を上書きし、DOM Iされていることである:経由で呼び出され
最後の配列[5]のみを含んでいます。
は、私はたくさんのことを試してみたが、この再帰関数は、これまでに最終製品である - それは要素を上書きしないと、すべての5つのアレイの部品が含まれているので、私はそれを微調整する助けてください。
編集:ちょうどFYI私は彼の元のコードは、さらにレベルを下に動作しません驚いここ http://www.viper007bond.com/2011/06/29/easily-create-xml-in-php-using-a-data-array/
から私のコードを適応させることを試みました。
おかげでそう私はそれを試してみましたが、それは実際にドキュメントの先頭に項目を追加します、順不同で – yoyoma
のでそれが遅くなってきたと私は非常にこれを把握することはできません。私は、XML文書内のすべてのノードを持っているが、彼らはすべてのルートノードとして「住宅」ノードの下に座っています。最初の兄弟シーケンシャル番号の配列位置には何かが間違っています。私はあなたが時間を割いて感謝http://pastebin.com/QafCSrq9 –
:):HTH、あなたはこのペーストビンの私の進行状況を確認することができます – yoyoma