如何将数组转换为 SimpleXML

How to convert array to SimpleXML

提问人: 提问时间:9/9/2009 最后编辑:Lightness Races in Orbit 更新时间:4/26/2023 访问量:503358

问:

如何在PHP中将数组转换为SimpleXML对象?

php xml 数组 simplexml

评论

6赞 cletus 9/9/2009
一个数组是什么?
1赞 Arvind Bhardwaj 11/3/2014
这很酷:viper007bond.com/2011/06/29/......

答:

3赞 Anthony 9/9/2009 #1

如果数组是关联的并且正确键入,那么首先将其转换为 xml 可能会更容易。像这样:

  function array2xml ($array_item) {
    $xml = '';
    foreach($array_item as $element => $value)
    {
        if (is_array($value))
        {
            $xml .= "<$element>".array2xml($value)."</$element>";
        }
        elseif($value == '')
        {
            $xml .= "<$element />";
        }
        else
        {
            $xml .= "<$element>".htmlentities($value)."</$element>";
        }
    }
    return $xml;
}

$simple_xml = simplexml_load_string(array2xml($assoc_array));

另一种方法是先创建基本 xml,例如

$simple_xml = simplexml_load_string("<array></array>");

然后,对于数组的每个部分,使用类似于我的文本创建循环的东西,而是对数组的每个节点使用 simplexml 函数“addChild”。

我稍后会尝试一下,并用两个版本更新这篇文章。

评论

0赞 Anthony 9/9/2009
我提到“<array></array>”的那一点让我意识到字符串版本需要类似的东西。基本上,数组必须在最外面有一个节点。让我睡一觉,我会有一些东西可以立即发现最初的错误。
227赞 ax. 9/9/2009 #2

一个简短的:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

结果

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

键和值是交换的 - 你可以在array_walk之前修复它。 需要 PHP 5。你可以改用,但你不会进入 XML。array_flip()array_walk_recursivearray_walk'stack' => 'overflow'

评论

56赞 understack 6/10/2010
如果 $test_array 的“more_another_array”像“another_array”一样,这将不起作用,因为键“another_array”未转换。因此,您将有多个“<溢出>堆栈</溢出>”。
11赞 Lode 6/6/2011
它不起作用,因为它不能翻转数组(如主数组内部)。array_flipanother_array
15赞 FMaz008 9/22/2011
“another_array”xml元素在哪里?一切都变平了:(
16赞 Martijn 4/5/2014
投反对票,因为仅当数组不包含相同值时才有效。array_flip
3赞 Josh Ribakoff 7/9/2014
投了反对票。翻转键/值不起作用,因为值不是唯一的,并且会相互覆盖。此外,尝试翻转多维数组会使 PHP 崩溃并显示“警告”。
0赞 w35l3y 9/9/2009 #3

如果详细的 xml 没有问题,您可以使用 xmlrpc_encode 从数组创建 xml。www.php.net/xmlrpc_encode

请注意,如果您使用关联键和/或数字键,则创建的 XML 会有所不同

<?php
// /params/param/value/struct/member
// there is a tag "member" for each element
// "member" contains a tag "name". its value is the associative key
$xml1 = xmlrpc_encode(array('a'=>'b','c'=>'d'));
$simplexml1 = simplexml_load_string($xml1);
print_r($xml1);
print_r($simplexml1);

// /params/param/value/array/data
// there is a tag "data" for each element
// "data" doesn't contain the tag "name"
$xml2 = xmlrpc_encode(array('a','b'));
$simplexml2 = simplexml_load_string($xml2);
print_r($xml2);
print_r($simplexml2);
?>

评论

0赞 danorton 7/13/2011
这个函数是不支持的,事实上,在我的 PHP 5.2.16 或 PHP 5.3.5 版本中没有提供。(返回“PHP 致命错误:调用未定义的函数 xmlrpc_encode()”)
0赞 w35l3y 7/13/2011
您必须在 php.ini 中取消注释以下行:extension=php_xmlrpc.dll
0赞 Mike S. 5/31/2012
@w35l3y我检查了我的ini。它甚至不包含该扩展,我使用的是 v 5.3.6。
39赞 onokazu 7/20/2010 #4
<?php
function array_to_xml(array $arr, SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($k, $v);
    }
    return $xml;
}

$test_array = array (
    'bla' => 'blub',
    'foo' => 'bar',
    'another_array' => array (
        'stack' => 'overflow',
    ),
);

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

评论

2赞 Adriano Varoli Piazza 10/14/2011
如果数组包含带有数字索引的内部数组,则此操作将失败。<0>...</0> 不是有效的 XML。
0赞 AlienWebguy 3/19/2012
@AdrianoVaroliPiazza只需在$k = (is_numeric($k)) ? 'item' : $k;foreach()
0赞 Bambax 2/26/2013
如果数组中的某个键被命名为“body”,则它不起作用 - 更准确地说,该键将被忽略并遍历。试图弄清楚原因。
0赞 Brilliand 2/22/2014
@Bambax 我能想到的唯一原因是,如果XML在以后的某个时候被解析为HTML。
421赞 Hanmant 5/11/2011 #5

这是 php 5.2 代码,它将任何深度的数组转换为 xml 文档:

Array
(
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Pune
                            [zip]=>411006
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Mumbai
                            [zip]=>400906
                        )   
                )

        )
)

生成的 XML 将如下所示:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Pune</city>
            <zip>411006</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Mumbai</city>
            <zip>400906</zip>
        </address>
    </student>
</student_info>

PHP 代码段

<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
    foreach( $data as $key => $value ) {
        if( is_array($value) ) {
            if( is_numeric($key) ){
                $key = 'item'.$key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

// initializing or creating array
$data = array('total_stud' => 500);

// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

// function call to convert array to xml
array_to_xml($data,$xml_data);

//saving generated xml file; 
$result = $xml_data->asXML('/file/path/name.xml');

?>

有关此代码段中使用的 SimpleXMLElement::asXML 的文档

评论

3赞 mbaynton 8/11/2014
此示例使用 htmlspecialchars 显式转义元素文本数据中的特殊字符,但 SimpleXMLElement::addChild 会自动将 xml 特殊字符转换为其 char 实体,以便可以省略 htmlspecialchars。有趣的是,这似乎不会导致双重转义数据。
1赞 Jonathan 10/23/2014
空数组值 [(string)“”] 将更改为空的 SimpleXML-Node,而不是留空。
3赞 Nicholas Blasgen 3/20/2015
@Alex,您的编辑 #5 会使示例失败。它在每个 <student> 记录之前插入 <item$x>,使 XML 输出不是作者想要的。也许提供您要解决的问题的示例,我们可以为这两种情况找到另一种解决方案。我花了一段时间才意识到作者的代码被修改了。
1赞 bart 10/18/2015
如何摆脱 itemxxx 节点?
5赞 zanderwar 9/6/2016
应该发布两个答案,这个修改后的答案打破了我的要求,因为它添加了.这次修订:stackoverflow.com/revisions/5965940/2 是我的赢家<itemN></itemN>
12赞 Frans van Asselt 7/16/2011 #6

这是我的条目,简单干净..

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLElement('<root/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}


header('Content-type: text/xml');
print array2xml($array);
144赞 Lalit 7/19/2011 #7

这里提供的答案只是将数组转换为带有节点的XML,您无法设置属性。我编写了一个 php 函数,允许您将数组转换为 php,并为 xml 中的特定节点设置属性。这里的缺点是你必须以一种特定的方式构造一个数组,几乎没有约定(只有当你想使用属性时)

下面的示例也允许您在 XML 中设置属性。

来源可以在这里找到: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php

<?php    
$books = array(
    '@attributes' => array(
        'type' => 'fiction'
    ),
    'book' => array(
        array(
            '@attributes' => array(
                'author' => 'George Orwell'
            ),
            'title' => '1984'
        ),
        array(
            '@attributes' => array(
                'author' => 'Isaac Asimov'
            ),
            'title' => 'Foundation',
            'price' => '$15.61'
        ),
        array(
            '@attributes' => array(
                'author' => 'Robert A Heinlein'
            ),
            'title' => 'Stranger in a Strange Land',
            'price' => array(
                '@attributes' => array(
                    'discount' => '10%'
                ),
                '@value' => '$18.00'
            )
        )
    )
);
/* creates 
<books type="fiction">
  <book author="George Orwell">
    <title>1984</title>
  </book>
  <book author="Isaac Asimov">
    <title>Foundation</title>
    <price>$15.61</price>
  </book>
  <book author="Robert A Heinlein">
    <title>Stranger in a Strange Land</title>
    <price discount="10%">$18.00</price>
  </book>
</books>
*/
?>

评论

11赞 FMaz008 9/23/2011
我很惊讶没有人对此做出反应。这个类非常有用,因为它与 simpleXMLElement 将生成的内容相反。因此,它为您提供了双向使用 SimpleXMLElement 的可能性。
4赞 Oleksandr IY 1/13/2014
我会将其标记为答案而不是当前答案。当前答案:不构建递归数组
2赞 user1433150 7/8/2014
不错的班级。我将第 128 行更改为,这样它就不会为空字符串附加新的文本节点,因此保留速记空标签格式,即 是而不是if(!is_array($arr)) {if(!is_array($arr) && $arr !== '') {'tag'=>''<tag/><tag></tag>
0赞 Vasil Popov 8/20/2015
这是迄今为止最好的答案。此外,它还具有具有相同键的多个项目的正确结构:第一个是节点名称键,然后它包含带有数字键的数组。(与汉曼特的答案相反)
1赞 Daryl Teo 11/29/2018
从作者那里找到了一个 github @Legionar github.com/digitickets/lalit/blob/master/src/Array2XML.php
4赞 Neil English 12/18/2011 #8

我使用我不久前编写的几个函数来生成 xml 以在 PHP 和 jQuery 等之间来回传递...... 两者都不使用任何其他框架,只是纯粹生成一个字符串,然后可以与 SimpleXML(或其他框架)一起使用......

如果它对任何人都有用,请:)使用它

function generateXML($tag_in,$value_in="",$attribute_in=""){
    $return = "";
    $attributes_out = "";
    if (is_array($attribute_in)){
        if (count($attribute_in) != 0){
            foreach($attribute_in as $k=>$v):
                $attributes_out .= " ".$k."=\"".$v."\"";
            endforeach;
        }
    }
    return "<".$tag_in."".$attributes_out.((trim($value_in) == "") ? "/>" : ">".$value_in."</".$tag_in.">" );
}

function arrayToXML($array_in){
    $return = "";
    $attributes = array();
    foreach($array_in as $k=>$v):
        if ($k[0] == "@"){
            // attribute...
            $attributes[str_replace("@","",$k)] = $v;
        } else {
            if (is_array($v)){
                $return .= generateXML($k,arrayToXML($v),$attributes);
                $attributes = array();
            } else if (is_bool($v)) {
                $return .= generateXML($k,(($v==true)? "true" : "false"),$attributes);
                $attributes = array();
            } else {
                $return .= generateXML($k,$v,$attributes);
                $attributes = array();
            }
        }
    endforeach;
    return $return;
}   

爱所有:)

2赞 frankey 2/27/2012 #9

只是对上面的一个函数进行编辑,当一个键是数字时,添加一个前缀“key_”

// initializing or creating array
$student_info = array(your array data);

// creating object of SimpleXMLElement
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");

// function call to convert array to xml
array_to_xml($student,$xml_student_info);

//saving generated xml file
$xml_student_info->asXML('file path and name');


function array_to_xml($student_info, &$xml_student_info) {
     foreach($student_info as $key => $value) {
          if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_student_info->addChild("$key");
                array_to_xml($value, $subnode);
            }
            else{
                $subnode = $xml_student_info->addChild("key_$key");
                array_to_xml($value, $subnode);
            }
          }
          else {
               if(!is_numeric($key)){
                    $xml_student_info->addChild("$key","$value");
               }else{
                    $xml_student_info->addChild("key_$key","$value");
               }
          }
     }
}
0赞 Kamil Dąbrowski 4/27/2012 #10
function array2xml($array, $xml = false){

    if($xml === false){

        $xml = new SimpleXMLElement('<?xml version=\'1.0\' encoding=\'utf-8\'?><'.key($array).'/>');
        $array = $array[key($array)];

    }
    foreach($array as $key => $value){
        if(is_array($value)){
            $this->array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}
1赞 JosephVasantPrakash 7/11/2012 #11

您可以直接在代码中使用以下函数,

    function artoxml($arr, $i=1,$flag=false){
    $sp = "";
    for($j=0;$j<=$i;$j++){
        $sp.=" ";
     }
    foreach($arr as $key=>$val){
        echo "$sp&lt;".$key."&gt;";
        if($i==1) echo "\n";
        if(is_array($val)){
            if(!$flag){echo"\n";}
            artoxml($val,$i+5);
            echo "$sp&lt;/".$key."&gt;\n";
        }else{
              echo "$val"."&lt;/".$key."&gt;\n";
         }
    }

}

使用第一个参数作为数组调用函数,第二个参数必须为 1,这将增加以获得完美的缩进,第三个参数必须为 true。

例如,如果要转换的数组变量是 $array 1,那么, 调用将是,调用函数应该用标签封装。<pre>

  artoxml($array1,1,true);   

请在执行文件后查看页面源代码,因为<和>符号不会显示在 html 页面中。

0赞 refeyd 8/1/2012 #12

我的答案,拼凑别人的答案。这应该可以纠正无法补偿数字键的问题:

function array_to_xml($array, $root, $element) {
    $xml = new SimpleXMLElement("<{$root}/>");
    foreach ($array as $value) {
        $elem = $xml->addChild($element);
        xml_recurse_child($elem, $value);
    }
    return $xml;
}

function xml_recurse_child(&$node, $child) {
    foreach ($child as $key=>$value) {
        if(is_array($value)) {
            foreach ($value as $k => $v) {
                if(is_numeric($k)){
                    xml_recurse_child($node, array($key => $v));
                }
                else {
                    $subnode = $node->addChild($key);
                    xml_recurse_child($subnode, $value);
                }
            }
        }
        else {
            $node->addChild($key, $value);
        }
    }   
}

该函数假定数组首先由数字键组成。如果你的数组有一个初始元素,你可以从函数中删除 and 语句,而只是传递。array_to_xml()foreach()$elemarray_to_xml()$xml

0赞 Jouni Mäkeläinen 10/9/2012 #13

我会评论第二个投票最多的答案,因为它不会保留结构,如果存在数字索引的内部数组,它会生成错误的 xml。

我基于它开发了自己的版本,因为无论数据结构如何,我都需要 json 和 xml 之间的简单转换器。我的版本保留了原始数组的数字键信息和结构。它通过将值包装到带有包含数字键的 key-attribute 的 value 命名元素来为数字索引值创建元素。

例如

array('test' => array(0 => 'some value', 1 => 'other'))

转换为

<test><value key="0">some value</value><value key="1">other</value></test>

我的 array_to_xml -function 版本(希望它能帮助某人:)

function array_to_xml($arr, &$xml) {
    foreach($arr as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml->addChild("$key");
            } else {
                $subnode = $xml->addChild("value");
                $subnode->addAttribute('key', $key);                    
            }
            array_to_xml($value, $subnode);
        }
        else {
            if (is_numeric($key)) {
                $xml->addChild("value", $value)->addAttribute('key', $key);
            } else {
                $xml->addChild("$key",$value);
            }
        }
    }
}   
3赞 mike 10/11/2012 #14

这里有一个为我起到了作用的功能:

只需用类似的东西来称呼它

echo arrayToXml("response",$arrayIWantToConvert);
function arrayToXml($thisNodeName,$input){
        if(is_numeric($thisNodeName))
            throw new Exception("cannot parse into xml. remainder :".print_r($input,true));
        if(!(is_array($input) || is_object($input))){
            return "<$thisNodeName>$input</$thisNodeName>";
        }
        else{
            $newNode="<$thisNodeName>";
            foreach($input as $key=>$value){
                if(is_numeric($key))
                    $key=substr($thisNodeName,0,strlen($thisNodeName)-1);
                $newNode.=arrayToXml3($key,$value);
            }
            $newNode.="</$thisNodeName>";
            return $newNode;
        }
    }
5赞 lcornea 10/24/2012 #15

我想要一个代码,它将数组中的所有元素视为属性,并将所有数组视为子元素。

所以对于类似的东西

array (
'row1' => array ('head_element' =>array("prop1"=>"some value","prop2"=>array("empty"))),
"row2"=> array ("stack"=>"overflow","overflow"=>"overflow")
);

我会得到这样的东西

<?xml version="1.0" encoding="utf-8"?>
<someRoot>
  <row1>
    <head_element prop1="some value">
      <prop2 0="empty"/>
    </head_element>
  </row1>
  <row2 stack="overflow" overflow="stack"/>
 </someRoot>

为了实现这一点,代码如下,但要非常小心,它是递归的,实际上可能会导致堆栈溢出:)

function addElements(&$xml,$array)
{
$params=array();
foreach($array as $k=>$v)
{
    if(is_array($v))
        addElements($xml->addChild($k), $v);
    else $xml->addAttribute($k,$v);
}

}
function xml_encode($array)
{
if(!is_array($array))
    trigger_error("Type missmatch xml_encode",E_USER_ERROR);
$xml=new SimpleXMLElement('<?xml version=\'1.0\' encoding=\'utf-8\'?><'.key($array).'/>');
addElements($xml,$array[key($array)]);
return $xml->asXML();
} 

您可能希望添加对数组长度的检查,以便在数据部分内设置某些元素,而不是作为属性。

1赞 Andrey 12/24/2012 #16
function toXML($data, $obj = false, $dom) {
    $is_first_level = false;
    if($obj === false) {
        $dom = new DomDocument('1.0');
        $obj = $dom;
        $is_first_level = true;
    }

    if(is_array($data)) {
        foreach($data as $key => $item) {
            $this->toXML($item, $obj->appendChild($dom->createElement($key)), $dom);
        }
    }else {
        $obj->appendChild($dom->createTextNode($data));
    }

    if($is_first_level) {
        $obj->formatOutput = true;
        return $obj->saveXML();
    }
    return $obj;
}

评论

0赞 altsyset 4/3/2014
这是创建 DOMDocument xml 的绝佳选择。谢谢@Andrey
0赞 ace 2/24/2013 #17

整个 XML 结构在 $data Array 中定义:

function array2Xml($data, $xml = null)
{
    if (is_null($xml)) {
        $xml = simplexml_load_string('<' . key($data) . '/>');
        $data = current($data);
        $return = true;
    }
    if (is_array($data)) {
        foreach ($data as $name => $value) {
            array2Xml($value, is_numeric($name) ? $xml : $xml->addChild($name));
        }
    } else {
        $xml->{0} = $data;
    }
    if (!empty($return)) {
        return $xml->asXML();
    }
}
0赞 Bharat Chodvadiya 3/16/2013 #18

如果您在 magento 中工作并且您有这种类型的关联数组

$test_array = array (
    '0' => array (
            'category_id' => '582',
            'name' => 'Surat',
            'parent_id' => '565',
            'child_id' => '567',
            'active' => '1',
            'level' => '6',
            'position' => '17'
    ),

    '1' => array (
            'category_id' => '567', 
            'name' => 'test',
            'parent_id' => '0',
            'child_id' => '576',
            'active' => '0',
            'level' => '0',
            'position' => '18'
    ),
);

那么最好将 Associative Array 转换为 XML 格式。在控制器文件中使用此代码。

$this->loadLayout(false);
//header ("content-type: text/xml");
$this->getResponse()->setHeader('Content-Type','text/xml');
$this->renderLayout();

$clArr2xml = new arr2xml($test_array, 'utf-8', 'listdata');
$output = $clArr2xml->get_xml();
print $output; 

class arr2xml
{
var $array = array();
var $xml = '';
var $root_name = '';
var $charset = '';

public function __construct($array, $charset = 'utf-8', $root_name = 'root')
{
    header ("content-type: text/xml");
    $this->array = $array;
    $this->root_name = $root_name;
    $this->charset = $charset;

    if (is_array($array) && count($array) > 0) {
        $this->struct_xml($array);

    } else {
        $this->xml .= "no data";
    }
}

public function struct_xml($array)
{
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $tag = ereg_replace('^[0-9]{1,}', 'item', $k); // replace numeric key in array to 'data'
            $this->xml .= "<$tag>";
            $this->struct_xml($v);
            $this->xml .= "</$tag>";
        } else {
            $tag = ereg_replace('^[0-9]{1,}', 'item', $k); // replace numeric key in array to 'data'
            $this->xml .= "<$tag><![CDATA[$v]]></$tag>";
        }
    }
}

public function get_xml()
{

    $header = "<?xml version=\"1.0\" encoding=\"" . $this->charset . "\"?><" . $this->root_name . ">";
    $footer = "</" . $this->root_name . ">";

    return $header . $this->xml . $footer;
}
}

我希望它对所有人都有所帮助。

9赞 CodePT 10/8/2013 #19

所以无论如何......我采用了 onokazu 的代码(谢谢!)并添加了在 XML 中具有重复标记的功能,它还支持属性,希望有人觉得它有用!

 <?php

function array_to_xml(array $arr, SimpleXMLElement $xml) {
        foreach ($arr as $k => $v) {

            $attrArr = array();
            $kArray = explode(' ',$k);
            $tag = array_shift($kArray);

            if (count($kArray) > 0) {
                foreach($kArray as $attrValue) {
                    $attrArr[] = explode('=',$attrValue);                   
                }
            }

            if (is_array($v)) {
                if (is_numeric($k)) {
                    array_to_xml($v, $xml);
                } else {
                    $child = $xml->addChild($tag);
                    if (isset($attrArr)) {
                        foreach($attrArr as $attrArrV) {
                            $child->addAttribute($attrArrV[0],$attrArrV[1]);
                        }
                    }                   
                    array_to_xml($v, $child);
                }
            } else {
                $child = $xml->addChild($tag, $v);
                if (isset($attrArr)) {
                    foreach($attrArr as $attrArrV) {
                        $child->addAttribute($attrArrV[0],$attrArrV[1]);
                    }
                }
            }               
        }

        return $xml;
    }

        $test_array = array (
          'bla' => 'blub',
          'foo' => 'bar',
          'another_array' => array (
            array('stack' => 'overflow'),
            array('stack' => 'overflow'),
            array('stack' => 'overflow'),
          ),
          'foo attribute1=value1 attribute2=value2' => 'bar',
        );  

        $xml = array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();

        echo "$xml\n";
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = FALSE;
        $dom->loadXML($xml);
        $dom->formatOutput = TRUE;
        echo $dom->saveXml();
    ?>

评论

0赞 StormeHawke 10/8/2013
注释您的更改以使代码更清晰可能会有所帮助;不过,不错的补充
0赞 achiever 6/21/2019
这对我有用 WP All Export。我不得不稍微改变is_numeric部分:if (is_numeric($k)) { $i = $k + 1; $child = $xml->addChild("_$i"); array_to_xml($v, $child); }
68赞 Francis Lewis 11/15/2013 #20

我找到了使用太多代码的所有答案。这是一种简单的方法:

function to_xml(SimpleXMLElement $object, array $data) {
    foreach ($data as $key => $value) {
        // if the key is an integer, it needs text with it to actually work.
        $valid_key  = is_numeric($key) ? "key_$key" : $key;
        $new_object = $object->addChild( 
            $valid_key, 
            is_array($value) ? null : htmlspecialchars($value) 
        );

        if (is_array($value)) {
            to_xml($new_object, $value);
        }
    }
}

然后是一个简单的问题,将数组发送到函数中,该函数使用递归,因此它将处理一个多维数组:

$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);

现在,$xml包含一个漂亮的 XML 对象,该对象基于您的数组,完全符合您的编写方式。

print $xml->asXML();

评论

10赞 wout 11/2/2016
我最喜欢这个解决方案。虽然,最好添加一个对数字键的测试,例如:.if ( is_numeric( $key ) ) $key = "numeric_$key";
0赞 Francis Lewis 6/22/2017
@wout 好渔获。添加。我做了一个 int cast 检查而不是 is_numeric,因为is_numeric可以给出一些(尽管技术上是预期的)结果,这些结果真的会让你失望。
0赞 Daantje 3/31/2020
我使用这个函数,但更改为有效的 UTF-8 编码。$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rootTag/>');
0赞 leo 4/14/2020
我也最喜欢这个解决方案,很简单:-)有一句话:您可能希望更改为 以防止$value包含需要 XML 编码的“&”等字符时失败。$object->addChild($key, $value);$object->addChild($key, htmlspecialchars($value));
0赞 Valeri 10/11/2020
它有效,但您必须添加三重等号:if ($key === (int) $key) { $key = "key_$key"; }
0赞 Francisco Luz 2/26/2014 #21

// Structered array for XML convertion.
$data_array = array(
  array(
    '#xml_tag' => 'a',
    '#xml_value' => '',
    '#tag_attributes' => array(
      array(
        'name' => 'a_attr_name',
        'value' => 'a_attr_value',
      ),
    ),
    '#subnode' => array(
      array(
        '#xml_tag' => 'aa',
        '#xml_value' => 'aa_value',
        '#tag_attributes' => array(
          array(
            'name' => 'aa_attr_name',
            'value' => 'aa_attr_value',
          ),
        ),
        '#subnode' => FALSE,
      ),
    ),
  ),
  array(
    '#xml_tag' => 'b',
    '#xml_value' => 'b_value',
    '#tag_attributes' => FALSE,
    '#subnode' => FALSE,
  ),
  array(
    '#xml_tag' => 'c',
    '#xml_value' => 'c_value',
    '#tag_attributes' => array(
      array(
        'name' => 'c_attr_name',
        'value' => 'c_attr_value',
      ),
      array(
        'name' => 'c_attr_name_1',
        'value' => 'c_attr_value_1',
      ),
    ),
    '#subnode' => array(
      array(
        '#xml_tag' => 'ca',  
        '#xml_value' => 'ca_value',
        '#tag_attributes' => FALSE,
        '#subnode' => array(
          array(
            '#xml_tag' => 'caa',
            '#xml_value' => 'caa_value',
            '#tag_attributes' => array(
              array(
                'name' => 'caa_attr_name',
                'value' => 'caa_attr_value',
              ),
            ),
            '#subnode' => FALSE,
          ),
        ),
      ),
    ),
  ),
);


// creating object of SimpleXMLElement
$xml_object = new SimpleXMLElement('<?xml version=\"1.0\"?><student_info></student_info>');


// function call to convert array to xml
array_to_xml($data_array, $xml_object);

// saving generated xml file
$xml_object->asXML('/tmp/test.xml');

/**
 * Converts an structured PHP array to XML.
 *
 * @param Array $data_array
 *   The array data for converting into XML.
 * @param Object $xml_object
 *   The SimpleXMLElement Object
 *
 * @see https://gist.github.com/drupalista-br/9230016
 * 
 */
function array_to_xml($data_array, &$xml_object) {
  foreach($data_array as $node) {
    $subnode = $xml_object->addChild($node['#xml_tag'], $node['#xml_value']);

    if ($node['#tag_attributes']) {
      foreach ($node['#tag_attributes'] as $tag_attributes) {
        $subnode->addAttribute($tag_attributes['name'], $tag_attributes['value']); 
      }
    }

    if ($node['#subnode']) {
      array_to_xml($node['#subnode'], $subnode);
    }
  }
}
4赞 jtrumbull 3/25/2014 #22

您可以使用我一直在研究的 XMLParser

$xml = XMLParser::encode(array(
    'bla' => 'blub',
    'foo' => 'bar',
    'another_array' => array (
        'stack' => 'overflow',
    )
));
// @$xml instanceof SimpleXMLElement
echo $xml->asXML();

将导致:

<?xml version="1.0"?>
<root>
    <bla>blub</bla>
    <foo>bar</foo>
    <another_array>
        <stack>overflow</stack>
    </another_array>
</root>
3赞 caiofior 4/15/2014 #23

我发现这个解决方案与原始问题相似

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);

class NoSimpleXMLElement extends SimpleXMLElement {
 public function addChild($name,$value) {
  parent::addChild($value,$name);
 }
}
$xml = new NoSimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();
15赞 Syl 5/19/2014 #24

另一个改进:

/**
* Converts an array to XML
*
* @param array $array
* @param SimpleXMLElement $xml
* @param string $child_name
*
* @return SimpleXMLElement $xml
*/
public function arrayToXML($array, SimpleXMLElement $xml, $child_name)
{
    foreach ($array as $k => $v) {
        if(is_array($v)) {
            (is_int($k)) ? $this->arrayToXML($v, $xml->addChild($child_name), $v) : $this->arrayToXML($v, $xml->addChild(strtolower($k)), $child_name);
        } else {
            (is_int($k)) ? $xml->addChild($child_name, $v) : $xml->addChild(strtolower($k), $v);
        }
    }

    return $xml->asXML();
}

用法:

$this->arrayToXML($array, new SimpleXMLElement('<root/>'), 'child_name_to_replace_numeric_integers');

评论

0赞 besciualex 2/18/2015
谢谢!您的函数返回任何 n 维数组的确切内容。
3赞 Ardi 7/15/2014 #25

以上大多数答案都是正确的。但是,我想出了这个答案,它解决了array_walk_recursive兼容性问题以及数字键问题。它还通过了我所做的所有测试:

function arrayToXML(Array $array, SimpleXMLElement &$xml) {

    foreach($array as $key => $value) {

        // None array
        if (!is_array($value)) {
            (is_numeric($key)) ? $xml->addChild("item$key", $value) : $xml->addChild($key, $value);
            continue;
        }   

        // Array
        $xmlChild = (is_numeric($key)) ? $xml->addChild("item$key") : $xml->addChild($key);
        arrayToXML($value, $xmlChild);
    }
}   

我还为此添加了一个测试类,您可能会发现它很有用:

class ArrayToXmlTest extends PHPUnit_Framework_TestCase {

    public function setUp(){ }
    public function tearDown(){ }

    public function testFuncExists() {
        $this->assertTrue(function_exists('arrayToXML'));
    }

    public function testFuncReturnsXml() {
        $array = array(
            'name' => 'ardi',
            'last_name' => 'eshghi',
            'age' => 31,
            'tel' => '0785323435'
        );

        $xmlEl =  new SimpleXMLElement('<root/>');
        arrayToXml($array, $xmlEl);

        $this->assertTrue($xmlEl instanceOf SimpleXMLElement);
    }

    public function testAssocArrayToXml() {

        $array = array(
            'name' => 'ardi',
            'last_name' => 'eshghi',
            'age' => 31,
            'tel' => '0785323435'
        );

        $expectedXmlEl = new SimpleXMLElement('<root/>'); 
        $expectedXmlEl->addChild('name', $array['name']);
        $expectedXmlEl->addChild('last_name', $array['last_name']);
        $expectedXmlEl->addChild('age', $array['age']);
        $expectedXmlEl->addChild('tel', $array['tel']);

        $actualXmlEl =  new SimpleXMLElement('<root/>');
        arrayToXml($array, $actualXmlEl);

        $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
    }

    public function testNoneAssocArrayToXml() {

        $array = array(
            'ardi',
            'eshghi',
            31,
            '0785323435'
        );

        // Expected xml value
        $expectedXmlEl = new SimpleXMLElement('<root/>'); 
        foreach($array as $key => $value)
            $expectedXmlEl->addChild("item$key", $value);

        // What the function produces       
        $actualXmlEl =  new SimpleXMLElement('<root/>');
        arrayToXml($array, $actualXmlEl);

        $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
    }

    public function testNestedMixArrayToXml() {

        $testArray = array(
            "goal",
            "nice",
            "funny" => array(
                'name' => 'ardi',
                'tel'   =>'07415517499',
                "vary",
                "fields" => array(
                    'small',
                    'email' => '[email protected]'
                ),

                'good old days'

            ),

            "notes" => "come on lads lets enjoy this",
            "cast" => array(
                'Tom Cruise',
                'Thomas Muller' => array('age' => 24)
            )
        );

        // Expected xml value
        $expectedXmlEl = new SimpleXMLElement('<root/>'); 
        $expectedXmlEl->addChild('item0', $testArray[0]);
        $expectedXmlEl->addChild('item1', $testArray[1]);
        $childEl = $expectedXmlEl->addChild('funny');
        $childEl->addChild("name", $testArray['funny']['name']);
        $childEl->addChild("tel", $testArray['funny']['tel']);
        $childEl->addChild("item0", "vary");
        $childChildEl = $childEl->addChild("fields");
        $childChildEl->addChild('item0', 'small');
        $childChildEl->addChild('email', $testArray['funny']['fields']['email']);
        $childEl->addChild("item1", 'good old days');
        $expectedXmlEl->addChild('notes', $testArray['notes']);
        $childEl2 = $expectedXmlEl->addChild('cast');
        $childEl2->addChild('item0', 'Tom Cruise');
        $childChildEl2 = $childEl2->addChild('Thomas Muller');
        $childChildEl2->addChild('age', $testArray['cast']['Thomas Muller']['age']);

        // What the function produces       
        $actualXmlEl = new SimpleXMLElement('<root/>');
        arrayToXml($testArray, $actualXmlEl);

        $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
    }
}      
4赞 drzaus 7/16/2014 #26

基于此处的其他所有内容,通过前缀 处理数字索引 + 属性,并可以将 xml 注入现有节点:@

法典

function simple_xmlify($arr, SimpleXMLElement $root = null, $el = 'x') {
    // based on, among others http://stackoverflow.com/a/1397164/1037948

    if(!isset($root) || null == $root) $root = new SimpleXMLElement('<' . $el . '/>');

    if(is_array($arr)) {
        foreach($arr as $k => $v) {
            // special: attributes
            if(is_string($k) && $k[0] == '@') $root->addAttribute(substr($k, 1),$v);
            // normal: append
            else simple_xmlify($v, $root->addChild(
                    // fix 'invalid xml name' by prefixing numeric keys
                    is_numeric($k) ? 'n' . $k : $k)
                );
        }
    } else {
        $root[0] = $arr;
    }

    return $root;
}//--   fn  simple_xmlify

用法

// lazy declaration via "queryparam"
$args = 'hello=4&var[]=first&var[]=second&foo=1234&var[5]=fifth&var[sub][]=sub1&var[sub][]=sub2&var[sub][]=sub3&var[@name]=the-name&var[@attr2]=something-else&var[sub][@x]=4.356&var[sub][@y]=-9.2252';
$q = array();
parse_str($val, $q);

$xml = simple_xmlify($q); // dump $xml, or...
$result = get_formatted_xml($xml); // see below

结果

<?xml version="1.0"?>
<x>
  <hello>4</hello>
  <var name="the-name" attr2="something-else">
    <n0>first</n0>
    <n1>second</n1>
    <n5>fifth</n5>
    <sub x="4.356" y="-9.2252">
      <n0>sub1</n0>
      <n1>sub2</n1>
      <n2>sub3</n2>
    </sub>
  </var>
  <foo>1234</foo>
</x>

奖励:格式化 XML

function get_formatted_xml(SimpleXMLElement $xml, $domver = null, $preserveWhitespace = true, $formatOutput = true) {
    // http://stackoverflow.com/questions/1191167/format-output-of-simplexml-asxml

    // create new wrapper, so we can get formatting options
    $dom = new DOMDocument($domver);
    $dom->preserveWhiteSpace = $preserveWhitespace;
    $dom->formatOutput = $formatOutput;
    // now import the xml (converted to dom format)
    /*
    $ix = dom_import_simplexml($xml);
    $ix = $dom->importNode($ix, true);
    $dom->appendChild($ix);
    */
    $dom->loadXML($xml->asXML());

    // print
    return $dom->saveXML();
}//--   fn  get_formatted_xml

评论

0赞 drzaus 11/29/2016
作为子元素而不是数字标签重复的更新版本:github.com/zaus/forms-3rdparty-xpost/blob/...
19赞 user492589 12/1/2014 #27

从 PHP 5.4

function array2xml($data, $root = null){
    $xml = new SimpleXMLElement($root ? '<' . $root . '/>' : '<root/>');
    array_walk_recursive($data, function($value, $key)use($xml){
        $xml->addChild($key, $value);
    });
    return $xml->asXML();
}

评论

0赞 phaberest 9/20/2016
它似乎是所选答案的直接副本,只是放入一个函数中。
0赞 Tyreal 6/26/2019
我会将htmlspecialchars()添加到addChild部分,如下所示: $xml->addChild($key, htmlspecialchars($value));
3赞 Gaius Baltar 12/2/2014 #28

其他解决方案:

$marray=array(....);
$options = array(
                "encoding" => "UTF-8",
                "output_type" => "xml", 
                "version" => "simple",
                "escaping" => array("non-ascii, on-print, markup")
                );
$xmlres = xmlrpc_encode_request('root', $marray, $options);
print($xmlres);

评论

0赞 Volomike 5/4/2016
这会产生意想不到的效果,即使用 methodCall、methodName、标量和向量等创建 RPC 样式的 XML。它并不是真正将数组转换为直接意义上的 XML。
0赞 Hassan Farooq 10/21/2020
xmlrpc_encode_request函数在 php 7.3 上未定义
1赞 user2381982 6/22/2015 #29
function array2xml(array $data, SimpleXMLElement $object = null, $oldNodeName = 'item')
{
    if (is_null($object)) $object = new SimpleXMLElement('<root/>');
    $isNumbered = true;
    $idx = 0;
    foreach ($data as $key => $x)
        if (is_string($key) || ($idx++ != $key + 0))
            $isNumbered = false;
    foreach ($data as $key => $value)
    {   
        $attribute = preg_match('/^[0-9]/', $key . '') ? $key : null;
        $key = (is_string($key) && !preg_match('/^[0-9]/', $key . '')) ? $key : preg_replace('/s$/', '', $oldNodeName);
        if (is_array($value))
        {
            $new_object = $object->addChild($key);
            if (!$isNumbered && !is_null($attribute)) $new_object->addAttribute('id', $attribute);
            array2xml($value, $new_object, $key);
        }
        else
        {
            if (is_bool($value)) $value = $value ? 'true' : 'false';
            $node = $object->addChild($key, htmlspecialchars($value));
            if (!$isNumbered && !is_null($attribute) && !isset($node->attributes()->id))
                $node->addAttribute('id', $attribute);
        }
    }
    return $object;
}

例如,此函数返回 <obj>...</obj><obj>...</obj> 用于数字索引的 XML 标记。

输入:

    array(
    'people' => array(
        'dog',
        'cat',
        'life' => array(
            'gum',
            'shoe',
        ),
        'fish',
    ),
    array('yeah'),
)

输出:

<root>
    <people>
        <people>dog</people>
        <people>cat</people>
        <life>
            <life>gum</life>
            <life>shoe</life>
        </life>
        <people>fish</people>
        <people>
            <people>yeah</people>
        </people>
    </people>
</root>

这应该满足所有共同的需求。也许您可以将第 3 行更改为:

$key = is_string($key) ? $key : $oldNodeName . '_' . $key;

或者,如果您使用的是以 s 结尾的复数形式:

$key = is_string($key) ? $key : preg_replace('/s$/', '', $oldNodeName);
1赞 Daniele Orlando 1/24/2016 #30

使用 FluidXML,您可以从 PHP 数组开始生成 SimpleXML 的 XML,其中...只有两行代码。

$fluidxml  = fluidxml($array);
$simplexml = simplexml_import_dom($fluidxml->dom());

示例数组可以是

$array = [ 'doc' => [
              'fruit' => 'orange',
              'cake'  => [
                   '@id' => '123', 
                   '@'   => 'tiramisu' ],
              [ 'pasta' => 'matriciana' ],
              [ 'pasta' => 'boscaiola'  ]
] ];

https://github.com/servo-php/fluidxml