我有这样的代码:
$dom = new DOMDocument(); // new dom object
$dom->formatOutput = TRUE; //tidy the output
$root = $dom->appendChild($dom->createElement('PaymentNotificationResponse'));
$sxe = simplexml_import_dom( $dom );
$xml_pay = $sxe->addChild('Payments');
$paymnt = $xml_pay->addChild('Payment');
$paymnt->addChild('PaymentLogId','123');
$paymnt->addChild('Status', '0');
print_r($sxe);
应该输出如下内容:
<PaymentNotificationResponse>
<Payments>
<Payment>
<PaymentLogId>123</PaymentLogId>
<Status>0</Status>
</Payment>
</Payments>
</PaymentNotificationResponse>
但是我得到的是:
SimpleXMLElement Object ( [Payments] => SimpleXMLElement Object ( [Payment] => SimpleXMLElement Object ( [PaymentLogId] => 123 [Status] => 0 ) ) )
即使我使用
print_r($sxe->asXML())
它只给出
1230年简简单单:
echo $sxe->asXML();
应该可以。
请注意,除非您有正确的标题,否则浏览器可能会将其读取为HTML。然后,您必须检查源代码以查看实际的XML。
要打印正确的输出,您应该打印$sxe->asXML(),但是如果您希望在浏览器上以XML格式显示输出,您还应该在php中打印标题:
header('Content-Type: application/xml; charset=utf-8')
对于示例来说,请检查下面的代码:
$dom = new DOMDocument(); // new dom object
$dom->formatOutput = TRUE; //tidy the output
$root = $dom->appendChild($dom->createElement('PaymentNotificationResponse'));
$sxe = simplexml_import_dom( $dom );
$xml_pay = $sxe->addChild('Payments');
$paymnt = $xml_pay->addChild('Payment');
$paymnt->addChild('PaymentLogId','123');
$paymnt->addChild('Status', '0');
print_r( header('Content-Type: application/xml; charset=utf-8') . $sxe->asXML());