Home >Backend Development >PHP Tutorial >PHP creates XML document through DOM_PHP tutorial
Recently, I used the zendframework framework to do a project, and I needed to take out the data in the database and generate an XML document. Here is a rough record of the process:
xml file:
1.
2.
3.
4.
5.
6.
7.
8.
9.
1. Create testController.php and add function.
1. public function projectAction(){
1. // XML-related routine
2. //$list refers to the data array in 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 list9. 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 body28. $this->_response->setHeader('Content-Type', 'text/xml; charset=utf-8')
29. ->setBody($output);
30. $this->_helper->layout->disableLayout();
31. }
This way you can output xml on the page.
If you want to save the xml, use $dom->save("filename.xml");
This article is from “Bob” blog