我正在尝试使用PHP(XML)在父元素中添加多个元素:
这就是我想要实现的目标:
<ns0:XmlInterchange xmlns:ns0="http://www.edi.com.au/EnterpriseService/" xmlns:ext="http://esb.dsv.com/ExtensionFunctions">
<ns0:InterchangeInfo>
<ns0:Date>2017-07-20 13:41:48</ns0:Date>
<ns0:XmlType>Verbose</ns0:XmlType>
<ns0:Source>
<ns0:EnterpriseCode>Company</ns0:Enterprisecode>
</ns0:Source>
</ns0:InterchangeInfo>
</ns0:XmlInterchange>
我有以下PHP代码:
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
$interchange = $xml->createElementNS('ns0', 'ns0:XmlInterchange');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns0', 'http://www.edi.com.au/EnterpriseService/');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ext', 'http://esb.dsv.com/ExtensionFunctions');
$xml->appendChild($interchange); //Add above attributes to our element. <!Xmlinterchange->
$item = $xml->createElement('ns0:InterchangeInfo');
$item->appendChild($xml->createElement('ns0:Date',$invoice_date));
$item->appendChild($xml->createElement('ns0:XmlType','Verbose'));
$item = $xml->createElement('ns0:Source');
$item->appendChild($xml->createElement('ns0:EnterpriseCode','Company'));
$interchange->appendChild($item);
unset($item); //Reset $item, so we can use the variable again.
但是,上面的输出:
<ns0:XmlInterchange xmlns:ns0="http://www.edi.com.au/EnterpriseService/" xmlns:ext="http://esb.dsv.com/ExtensionFunctions">
<ns0:Source>
<ns0:EnterpriseCode>Company</ns0:EnterpriseCode>
</ns0:Source>
</ns0:XmlInterchange>
我希望能够将<ns0:Source>
元素放在<ns0:InterChangeInfo>
元素中,但与其他元素一起使用。
答案 0 :(得分:0)
您必须将<ns0:Source>
附加到<ns0:InterchangeInfo>
。之后,将<ns0:InterchangeInfo>
附加到<ns0:XmlInterchange>
。
请记住:->appendChild()
表示不附加但附加在内部。所以$a->appendChild($b);
表示你将b附加到。
尝试:
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
$interchange = $xml->createElementNS('ns0', 'ns0:XmlInterchange');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns0', 'http://www.edi.com.au/EnterpriseService/');
$interchange->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ext', 'http://esb.dsv.com/ExtensionFunctions');
$item = $xml->createElement('ns0:InterchangeInfo');
$item->appendChild($xml->createElement('ns0:Date',$invoice_date));
$item->appendChild($xml->createElement('ns0:XmlType','Verbose'));
$source = $xml->createElement('ns0:Source');
$source->appendChild($xml->createElement('ns0:EnterpriseCode','Company'));
$item->appendChild($source);
$interchange->appendChild($item);
$xml->appendChild($interchange);