我有一个使用以下示例构建的 XML 字符串:
//add root
$Add = $dom->appendChild($dom->createElement('Add'));
//pCase
$pCase = $Add->appendChild($dom->createElement('pCase'));
//add elements
$LeadGenID = $pCase->appendChild($dom->createElement('LeadGenID'));
$LeadGenID->appendChild($dom->createTextNode('22'));
$Debtor = $pCase->appendChild($dom->createElement('Debtor'));
//address fields
$Addresses = $Debtor->appendChild($dom->createElement('Addresses'));
$Address = $Addresses->appendChild($dom->createElement('Address'));
//array of address objects should go here
$test1 = $dom->saveXML();
$sxe = simplexml_load_string($test1);
if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}
$dom = new DOMDocument('1.0', 'utf-8');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);
echo $dom->save('application.xml');
然后在我的 XML 中输出以下内容:
<Add>
<pCase>
<LeadGenID>22</LeadGenID>
<Debtor>
<Addresses><Address/></Addresses>
</Debtor>
</pCase>
我还需要将一个数组输出到这个 XML 中,这样完整的输出如下:
<Add>
<pCase>
<LeadGenID>22</LeadGenID>
<Debtor>
<Addresses>
<Address>
<Street>Some street</Street>
<Postcode>Some postcode</Postcode>
</Address>
</Addresses>
</Debtor>
</pCase>
我试图用
$address_array = array (
$_POST['Street'] => 'Street',
$_POST['Postcode'] => 'Postcode'
);
$xml = new SimpleXMLElement('<Address/>');
array_walk_recursive($address_array, array ($xml, 'addChild'));
但此时我完全迷失了。至少可以说,我得到的 API 在文档上很少,但我越来越接近它,但我需要输入地址作为网关的数组。我是 PHP 新手,因为我主要是一名前端开发人员,通常只在 PHP 中完成简单的联系表格等。
如何输出上面给出的 XML 示例?
谢谢