【发布时间】:2018-09-20 11:53:19
【问题描述】:
我正在尝试将 JSON 转换为 XML 格式以通过 API 发送。我有多个有效的对象,但这些 JSON 数组不是多维数组,所以它有效。但是当我在更深的数组上尝试这个函数时,它就不起作用了。
数组:
public function create_order_direct($plan_id) {
return $this->__request(__FUNCTION__, [
"media_id" => 'FACE',
"client_id" => 'HELL',
"agreement_id" => '*****',
"client_reference" => ****,
"client_contact" => "******",
"plan_number" => ******,
"plan_name" => "TEST",
"cuid" => ******,
"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",
]);
}
代码:
$xml = new \SimpleXMLElement('<marathon/>');
//For each element in the array add it as a child node to the xml object.
foreach ($request as $k => $v) {
if (is_array($v)) { //nested array
$xml->addChild($k);
} else {
$xml->addChild($k, $v);
}
}
echo"<pre>";
print_r($xml);
die;
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->encoding = "UTF-8";
$dom->formatOutput = true;
return $dom->saveXML();
输出:
SimpleXMLElement Object
(
[media_id] => FACE
[client_id] => HELL
[agreement_id] => REDP
[client_reference] => 123456
[client_contact] => Asim Tariq
[plan_number] => 408
[plan_name] => TEST
[cuid] => 123456
[status] => P
[colour] => 0
[insertion] => SimpleXMLElement Object
(
)
[comment] => THIS IS A TEST DO NOT FAKTURER
[type] => create_order_direct
[password] => *********
[company_id] => REDP
)
我需要什么(预期输出):
<marathon>
<media_id>***</media_id>
<agreement_id>***</agreement_id>
<client_reference>***</client_reference>
<client_contact>***</client_contact>
<plan_number>***</plan_number>
<plan_name>***</plan_name>
<cuid>***</cuid>
<status>***</status>
<colour>***</colour>
<insertion>
<insertion_date>2016-11-20</insertion_date>
<end_date>201-11-21</end_date>
<client_reference>123</client_reference>
<price_row>
<price_code>000</price_code>
<number_of_units>2500000</number_of_units>
<gross>1000</gross>
<discount>
<discount_1>100</discount_1>
</discount>
<comment>This is a comment!</comment>
</price_row>
</insertion>
</marathon>
insertion 部分有问题,看起来没有被迭代。
更新:(using: echo $xml->asXML();)(我看到“插入”-->“价格行”->“折扣”中缺少):
FACEREDP123456Asim Tariq408TEST123456P0这是一个测试不要FAKTURERcreate_order_direct*********REDP
【问题讨论】:
-
您的代码生成的实际 XML 输出是什么?不要使用
print_r调试 SimpleXML 对象 - 它不会显示所有内容。 -
@hassan: 公共函数 addChild ($name, $value = null, $namespace = null) {}
-
@iainn。 var_dump() 给出相同的值
-
也不要使用
var_dump(或var_export等)。 SimpleXML 对象的行为与其他对象不同,尝试使用内置调试功能来查看它们并不总是有效。改为运行echo $xml->asXML(),它会显示实际构建的内容。 -
@iainn。它输出没有包含 dept 的数组的所有内容。我会在问题中发布它