最近用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” 博客