我有一个关于如何使用DOMDocument和创建XML的问题。
我有一个PHP程序
我遇到的问题是,XML看起来很好,直到我尝试将最后的文档返回给客户端。我使用的是saveXML(),所得到的文件包含< >等等。当我尝试对file ()进行保存时,我也会得到这些结果。已经在PHP板上搜索了几个小时。
这是我的密码:
<?php
header('Content-type: text/xml');
// **** Load XML ****
$xml = simplexml_load_file('Test1.xml');
// Instantiate class; work with single instance
$myAddress = new myAddressClass;
$domDoc = new DOMDocument('1.0', 'UTF-8');
$domDoc->formatOutput = true;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
//Go through each row of XML and process each address
foreach($xml->Row as $row)
{
//fire off function against instance
// returns SimpleXMLElement
$resultXMLNode = $myAddress->buildRequest() ;
// need XML representation of node
$subNode = $addressXML->asXML();
// strip out extraneous XML def
$cleanSubNode = str_replace('<?xml version="1.0"?>', '', $subNode);
// create new node
$subElt = $domDoc->createElement('MyResponse', $cleanSubNode );
//append subElmt node
$rootNode->appendChild($subElt);
}
// need full XML doc properly formatted/valid
$domDoc->saveXML();
?>顺便说一句,我正在将XML返回给客户端,这样我就可以通过jQuery生成HTML了。
任何帮助都将不胜感激。
而且,如果任何人都能提供一种更有效的方法来做这件事,那就太棒了:)
谢谢。
抢夺
发布于 2011-11-05 08:29:02
要将XML (作为字符串)追加到另一个元素中,您可以创建一个文档片段,然后可以追加该文档片段:
// create new node
$subElt = $domDoc->createElement('MyResponse');
// create new fragment
$fragment = $domDoc->createDocumentFragment();
$fragment->appendXML($cleanSubNode);
$subElt->appendChild($fragment);这将将原始XML转换为domdocument元素,它正在使用DOMDocumentFragment::appendXML函数。
编辑:在您的用例中(对注释),您可以直接使用simplexml对象并将其放入您的导入文档中:
// create subelement
$subElt = $domDoc->createElement('MyResponse');
// import simplexml document
$subElt->appendChild($domDoc->importNode(dom_import_simplexml($resultXMLNode), true));
// We insert the new element as root (child of the document)
$domDoc->appendChild($subElt);不需要将响应转换为字符串并使用它执行替换操作。
https://stackoverflow.com/questions/8018646
复制相似问题