我在创建多维SimpleXMLElement时遇到了一些麻烦,它可以与简单数组一起很好地工作,但是当存在多维数组时,SimpleXMLElement不会以多维SimpleXMLEelement编写。像这样:
createXML函数:
public function createXML($data, $root = null) {
$xml = new \SimpleXMLElement($root ? '<' . $root . '/>' : '<marathon/>');
array_walk_recursive($data, function($value, $key)use($xml){
$xml->addChild($key, $value);
});
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->encoding = "UTF-8";
$dom->formatOutput = true;
print $dom->saveXML();
}
打印:
<marathon>
<media_id>FACE</media_id>
<agreement_id>****</agreement_id>
<client_reference>123456</client_reference>
<client_contact>Asim</client_contact>
<plan_number>407</plan_number>
<plan_name>TEST</plan_name>
<cuid>123456</cuid>
<status>P</status>
<colour>0</colour>
<insertion_date>2018-09-19</insertion_date>
<end_date>2018-09-20</end_date>
<client_reference>1234</client_reference>
<price_code>0</price_code>
<number_of_units>250000</number_of_units>
<gross>1000</gross>
<comment>THIS IS A TEST DO NOT FAKTURER</comment>
</marathon>
当我想要的是:
<marathon>
<media_id>FACE</media_id>
<agreement_id>REDP</agreement_id>
<client_reference>123456</client_reference>
<client_contact>Asim Tariq</client_contact>
<plan_number>407</plan_number>
<plan_name>TEST</plan_name>
<cuid>123456</cuid>
<status>P</status>
<colour>0</colour>
<insertion>
<insertion_date>2018-09-19</insertion_date>
<end_date>2018-09-20</end_date>
<client_reference>1234</client_reference>
<price_row>
<price_code>0</price_code>
<number_of_units>250000</number_of_units>
<gross>1000</gross>
<comment>THIS IS A TEST DO NOT FAKTURER</comment>
</price_row>
</insertion>
</marathon>
如何使用createXML
中的代码来管理它? XML不具有多维性?
这是我发送的数组 $data:
[
"media_id" => 'FACE',
"agreement_id" => 'REDP',
"client_reference" => 123456,
"client_contact" => "Asim Tariq",
"plan_number" => 407,
"plan_name" => "TEST",
"cuid" => 123456,
"status" => 'P',
"colour" => 0,
"insertion" => [
"insertion_date" => '2018-09-19',
"end_date" => '2018-09-20',
"client_reference" => 1234,
"price_row" => [
"price_code" => 000,
"number_of_units" => 250000,
"gross" => 1000,
"discount" => [
],
"comment" => "THIS IS A TEST DO NOT FAKTURER",
],
],
]
答案 0 :(得分:2)
根据array_walk_recursive
的{{3}},“拥有数组的任何键都不会传递给函数”。
编写一个递归函数,如果该值是数组,则将其添加到子元素。例如:
private function addXMLData(\SimpleXMLElement $xml, array $data)
{
array_walk($data, function($value, $key) use($xml){
if (is_array($value)) {
$child = $xml->addChild($key);
self::addXMLData($child, $value);
} else {
$xml->addChild($key, $value);
}
});
}
public function createXML($data, $root = null) {
$xml = new \SimpleXMLElement($root ? '<' . $root . '/>' : '<marathon/>');
self::addXMLData($xml, $data);
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->encoding = "UTF-8";
$dom->formatOutput = true;
print $dom->saveXML();
}