PHP创建XML的方法示例【基于DOMDocument类及SimpleXMLElement类】

本文实例讲述了PHP创建XML的方法,分享给大家供大家参考,具体如下:

使用DOMDocument类创建xml

config.php

  1. <?php
  2. $doc = new DOMDocument('1.0','utf-8');
  3. $doc->formatOutput = true;
  4. //创建标签
  5. $mysql = $doc->createElement("mysql");
  6. $host = $doc->createElement("host");
  7. $username = $doc->createElement("username");
  8. $password = $doc->createElement("password");
  9. $database = $doc->createElement("database");
  10. //创建标签内容
  11. $hostval = $doc->createTextNode("127.0.0.1");
  12. $usernameval = $doc->createTextNode("root");
  13. $passwordval = $doc->createTextNode("1234");
  14. $databaseval = $doc->createTextNode("test");
  15. //绑定标签和内容
  16. $host->appendChild($hostval);
  17. $username->appendChild($usernameval);
  18. $password->appendChild($passwordval);
  19. $database->appendChild($databaseval);
  20. //关联标签之间的关系
  21. $doc->appendChild($mysql);
  22. $mysql->appendChild($host);
  23. $mysql->appendChild($username);
  24. $mysql->appendChild($password);
  25. $mysql->appendChild($database);
  26. $doc->save("config.xml");

config.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mysql>
  3. <host>127.0.0.1</host>
  4. <username>root</username>
  5. <password>1234</password>
  6. <database>test</database>
  7. </mysql>

使用simplexml方法创建xml

config.php

  1. <?php
  2. $mysql = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><mysql></mysql>');
  3. $host = $mysql->addchild("host","127.0.0.1");
  4. $host->addAttribute("note","localhost");
  5. $mysql->addchild("username","root");
  6. $mysql->addchild("password","1234");
  7. $mysql->addchild("database","test");
  8. header("Content-type:text/xml;charset=utf-8");
  9. echo $mysql->asXml();
  10. $mysql->asXml("config.xml");

config.xml

  1. <mysql>
  2. <host note="localhost">127.0.0.1</host>
  3. <username>root</username>
  4. <password>1234</password>
  5. <database>test</database>
  6. </mysql>