簡體   English   中英

如何使用PHP將具有相同重復元素的子數組的數組輸出到XML中

[英]How to output array with subarrays with same repeating element into XML with PHP

我正在嘗試采用以下數組並將其轉換為 XML。 在大多數情況下它有效。

$test_array = array (
  'akey' => 'auth_key',
  'cmd' => 'command',
  'aid' => 'account_id',
  'scode' => 'short_code',
  'key' => 'keyword',
  'words' => 'message',
  'contacts' => [
    '1' => 'contact_number',
    '2' => 'contact_number'
  ]
);

//edit: code for output
$dataXml = new SimpleXMLElement('<sms/>');
array_walk_recursive($test_array, array ($dataXml, 'addChild'));
print $dataXml->asXML();

輸出是

<sms>
    <auth_key>akey</auth_key>
    <command>cmd</command>
    <account_id>aid</account_id>
    <short_code>scode</short_code><keyword>key</keyword>
    <message>words</message>
    <contact_number>1</contact_number>
    <contact_number>2</contact_number>
</sms>

但需要如下

<sms>
    <auth_key>akey</auth_key>
    <command>cmd</command>
    <account_id>aid</account_id>
    <short_code>scode</short_code><keyword>key</keyword>
    <message>words</message>
    <contacts>
        <contact_number>1</contact_number>
        <contact_number>2</contact_number>
    </contacts>
</sms>

我已經看到使用 DOMDocument 的解決方案,也許我只需要那樣做,但我希望有一個更簡單的解決方案。

我還嘗試創建聯系人,因為它是自己的 XML,然后將其直接放入 XML,似乎這可能超出頂部的標簽<?xml version="1.0"?> XML 文件,但即使我能設法擺脫它,我也不確定它甚至可以處理特定的 XML 需要。

我能夠在@Nigel Ren的幫助下得到答案,他們參考了https://stackoverflow.com/a/3289602/1213708的答案。

<?php
function array_to_xml(array $arr, SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? $this->array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($v, $k); // this is the important part where the $key/$value is flipped and fixes the issue I was having
    }
    return $xml;
}

$test_array = array (
  'akey' => 'auth_key',
  'cmd' => 'command',
  'aid' => 'account_id',
  'scode' => 'short_code',
  'key' => 'keyword',
  'words' => 'message',
  'contacts' => [
    '1' => 'contact_number',
    '2' => 'contact_number'
  ]
);

echo array_to_xml($test_array, new SimpleXMLElement('<sms/>'))->asXML();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM