PHP通过DOM创建XML文档
最近用zendframework框架做项目,要把数据库中的数据拿出来生成XML文档。在此大概记录一下过程:
xml文件:
1. <?xml version="1.0" encoding="UTF-8"?>
2. <data>
3. <project id="1"><![CDATA[Docker JCP1]]></project>
4. <project id="2"><![CDATA[Docker JCP2]]></project>
5. <project id="3"><![CDATA[Docker JCP3]]></project>
6. <project id="4"><![CDATA[Docker JCP4]]></project>
7. <project id="5"><![CDATA[Docker JCP5]]></project>
8. <project id="6"><![CDATA[Docker JCP6]]></project>
9. </data>
1.建testController.php,添加function.
1. public function projectAction(){
1. // XML-related routine
2. //$list 指xml中的数据数组。
3. $dom = new DOMDocument('1.0', 'utf-8');
4. // create root element
5. $root = $dom->createElement("data");
6. $dom->appendChild($root);
7.
8. //project name xml list
9. foreach ($list as $project_item){
10. // create child element
11. $projectname = $dom->createElement('project');
12. $root->appendChild($projectname);
13.
14. // create CDATA section
15. $cdata = $dom->createCDATASection($project_item->name);
16. $projectname->appendChild($cdata);
17.
18. $id = $dom->createAttribute("id");
19. $projectname->appendChild($id);
20.
21. // create attribute value node
22. $idValue = $dom->createTextNode($project_item->project_id);
23. $id->appendChild($idValue);
24. }
25. $output = $dom->saveXML();
26.
27. // Setting up headers and body
28. $this->_response->setHeader('Content-Type', 'text/xml; charset=utf-8')
29. ->setBody($output);
30. $this->_helper->layout->disableLayout();
31. }
这样就可以在页面上输出xml了。
如果要把xml保存,用$dom->save("filename.xml");
本文出自 “Bob” 博客
补充:Web开发 , php ,