如何将数组转换为PHP中的SimpleXML对象?
当前回答
我认为上面所有的解决方案都很好,但我看到目前为止,它并没有真正创建一个准确的格式良好的XML,因为数组键与$my_array[main_node][multiple_values][] = ARRAY ('id' => '1')然后转换为
<main_node>
<multiple_values>
<0>
<id>1 test</id>
</0>
</multiple_values>
<multiple_values>
<1>
<id>2 test</id>
</1>
</multiple_values>
</main_node>
这是XML解析器方面的一个问题……
I should be like this:
<main_node>
<multiple_values>
<id>1 test</id>
</multiple_values>
<multiple_values>
<id>2 test</id>
</multiple_values>
</main_node>
如果你用load_simple_xml来解析…你会得到完全相同的数组/对象结构。
我的函数还自动创建正确的根节点。
// Code to convert php array to xml document 20211112
function array2xml(array $data, $xml_class_obj = '', $group_by_parent_allowed = '', $options = array())
{
if(!$xml_class_obj) :
$is_root = 1;
$xml_class_obj = new XMLWriter();
$xml_class_obj->openMemory();
$xml_class_obj->setIndent(TRUE);
$xml_class_obj->setIndentString(' ');
if($options['encoding'] != '') $xml_class_obj->startDocument('1.0', $options['encoding']);
else $xml_class_obj->startDocument('1.0');
endif;
foreach ($data as $key => $value) {
if (is_array($value)) { // IS ARRAY
// check if allow below keys are int, if yes group them to same parent tree
$group_by_parent = $key;
foreach(array_keys($value) as $c_keys) :
if(!is_int($c_keys)) $group_by_parent = '';
endforeach;
if(empty($group_by_parent)) $xml_class_obj->startElement($key);
if($group_by_parent_allowed != '') $xml_class_obj->startElement($group_by_parent_allowed);
$this->array2xml($value, $xml_class_obj, $group_by_parent, $options);
if(empty($group_by_parent)) $xml_class_obj->endElement();
} else { // IS VALUE
if(is_string($value)) :
$xml_class_obj->startElement($key);
$xml_class_obj->writeCData($value);
$xml_class_obj->endElement();
else :
$xml_class_obj->writeElement($key, $value);
endif;
}
} // foreach
if($group_by_parent_allowed != '') $xml_class_obj->endElement();
if($is_root == 1) :
$xml_class_obj->endDocument();
return $xml_class_obj->outputMemory();
else :
return $xml_class_obj;
endif;
}
// usage
$ary_new_xml = array();
$ary_new_xml['order']['customer']['customerid'] = '123456';
$ary_new_xml['order']['customer']['customertype'] = 15;
$ary_new_xml['order']['orderprio'] = 2;
$ary_new_xml['order']['orderpos'][] = array('sku' => 9999910001111, 'quantity' => 3);
$ary_new_xml['order']['orderpos'][] = array('sku' => 9999910002222, 'quantity' => 1);
echo array2xml($ary_new_xml,'','',array('enconding' => 'UTF-8'));
结果:
<?xml version="1.0" encoding="UTF-8"?>
<order>
<customer>
<customerid>82936639</customerid>
<customertype>15</customertype>
</customer>
<orderprio>2</orderprio>
<orderpos>
<sku>9999910001111</sku>
<quantity>3</quantity>
</orderpos>
<orderpos>
<sku>9999910002222</sku>
<quantity>1</quantity>
</orderpos>
</order>
我希望这能帮助到一些人;)
其他回答
<?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();
这里有一个函数帮我解决了这个问题:
就像这样叫它
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;
}
}
如果冗长的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);
?>
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;
}
以上答案大部分是正确的。然而,我想出了这个答案,它解决了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' => 'ardi.eshghi@gmail.com'
),
'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());
}
}
推荐文章
- 如何找到一个值的数组索引?
- 如何在Android中获得一个RadioGroup的选定索引
- Python csv字符串到数组
- 编写器更新和安装之间有什么区别?
- 本地机器上的PHP服务器?
- 如何评论laravel .env文件?
- 使用Java在原语数组中查找最大/最小值
- 对象作为React子对象无效。如果要呈现子元素的集合,请使用数组
- 越界访问数组有多危险?
- 在PHP中检测移动设备的最简单方法
- 如何在树枝模板中呈现DateTime对象
- 如何删除查询字符串,只得到URL?
- XML Schema minOccurs / maxOccurs默认值
- 您是否可以“编译”PHP代码并上传一个二进制文件,该文件将由字节码解释器运行?
- 非法字符串偏移警告PHP