繁体   English   中英

PHP如何将数组转换为XML

[英]PHP how to convert array to xml

我正在从数组创建xml文件。 我找到了链接“ 如何将数组转换为SimpleXML”,并尝试使用用户Hanmant提供的ans创建xml。

输入数组

$data = array(
  'Pieces' => array(
    'Piece' => array(
      array(
        'PieceID' => '1',
        'Weight' => '0.5',
      ),
      array(
        'PieceID' => '2',
        'Weight' => '2.0',
      ),
    ),
  ),
);    

但是我得到的结果是

<Pieces>
  <Piece>
     <item0>
        <PieceID>1</PieceID>
        <Weight>0.5</Weight>
     </item0>
     <item1>
        <PieceID>2</PieceID>
        <Weight>2.0</Weight>
     </item1>
  </Piece>
</Pieces>

我怎样才能得到像

<Pieces>
  <Piece>
     <PieceID>1</PieceID>
     <Weight>0.5</Weight>
  </Piece>
  <Piece>
     <PieceID>2</PieceID>
     <Weight>2.0</Weight>
  </Piece>
</Pieces>

通读您提供的链接上的所有答案,这里提出了几种比接受的答案更好的解决方案。

例如,那里的答案之一就是此类: http : //www.lalit.org/lab/convert-php-array-to-xml-with-attributes/

它不仅允许您在其中包含属性,而且还允许您根据需要生成XML。

检查这个网站,您可能会得到查询的答案

http://www.phpro.org/classes/PHP-Recursive-Array-To-XML-With-DOM.html

您拥有的数组结构与Hanmant答案不同 ,因此您为该工作选择了错误的函数。

但是,当您使用递归函数执行此操作时,您只需要使用SimpleXMLElement的代码很少:

$data = array(
    'Pieces' => array(
        'Piece' => array(
            array(
                'PieceID' => '1',
                'Weight'  => '0.5',
            ),
            array(
                'PieceID' => '2',
                'Weight'  => '2.0',
            ),
        ),
    ),
);

$xml = create($data);

具有以下create定义:

function create($from, SimpleXMLelement $parent = null, $tagName = null)
{
    if (!is_array($from)) {
        if ($tagName === null) {
            $parent[0] = (string) $from;
        } else {
            $parent->addChild($tagName, (string) $from);
        }
        return $parent;
    }

    foreach ($from as $key => $value) {
        if (is_string($key)) {
            if ($parent === null) {
                $parent = new SimpleXMLElement("<$key/>");
                create($value, $parent);
                break;
            }
            create($value, $parent, $key);
        } else {
            create($value, $parent->addChild($tagName));
        }
    }

    return $parent;
}

此函数首先处理字符串值以设置元素的节点值。 然后遍历至少具有单个元素或多个元素标记名的数组。 如果文档尚不存在,则会创建该文档并将子元素添加到其中(递归)。 否则,仅添加子元素(递归)。

这是示例代码,几乎没有错误处理,因此请务必遵循问题中概述的数组的格式。

输出(美化):

<?xml version="1.0"?>
<Pieces>
  <Piece>
    <PieceID>1</PieceID>
    <Weight>0.5</Weight>
  </Piece>
  <Piece>
    <PieceID>2</PieceID>
    <Weight>2.0</Weight>
  </Piece>
</Pieces>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM