繁体   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