PHP通过DOM创建XML文档_PHP教程
xml文件:
1.
2.
3.
4.
5.
6.
7.
8.
9.
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” 博客