PHP創(chuàng)建XML的方法示例【基于DOMDocument類及SimpleXMLElement類】
本文實例講述了PHP創(chuàng)建XML的方法。分享給大家供大家參考,具體如下:
使用DOMDocument類創(chuàng)建xml
config.php
<?php $doc = new DOMDocument('1.0','utf-8'); $doc->formatOutput = true; //創(chuàng)建標簽 $mysql = $doc->createElement("mysql"); $host = $doc->createElement("host"); $username = $doc->createElement("username"); $password = $doc->createElement("password"); $database = $doc->createElement("database"); //創(chuàng)建標簽內(nèi)容 $hostval = $doc->createTextNode("127.0.0.1"); $usernameval = $doc->createTextNode("root"); $passwordval = $doc->createTextNode("1234"); $databaseval = $doc->createTextNode("test"); //綁定標簽和內(nèi)容 $host->appendChild($hostval); $username->appendChild($usernameval); $password->appendChild($passwordval); $database->appendChild($databaseval); //關(guān)聯(lián)標簽之間的關(guān)系 $doc->appendChild($mysql); $mysql->appendChild($host); $mysql->appendChild($username); $mysql->appendChild($password); $mysql->appendChild($database); $doc->save("config.xml");
config.xml
<?xml version="1.0" encoding="utf-8"?> <mysql> <host>127.0.0.1</host> <username>root</username> <password>1234</password> <database>test</database> </mysql>
使用simplexml方法創(chuàng)建xml
config.php
<?php $mysql = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><mysql></mysql>'); $host = $mysql->addchild("host","127.0.0.1"); $host->addAttribute("note","localhost"); $mysql->addchild("username","root"); $mysql->addchild("password","1234"); $mysql->addchild("database","test"); header("Content-type:text/xml;charset=utf-8"); echo $mysql->asXml(); $mysql->asXml("config.xml");
config.xml
<mysql> <host note="localhost">127.0.0.1</host> <username>root</username> <password>1234</password> <database>test</database> </mysql>
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP針對XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
- PHP使用DOMDocument類生成HTML實例(包含常見標簽元素)
- 如何解決php domdocument找不到的問題
- PHP中使用DOMDocument來處理HTML、XML文檔的示例
- PHP讀取XML文件的方法實例總結(jié)【DOMDocument及simplexml方法】
- PHP基于DOMDocument解析和生成xml的方法分析
- PHP 中 DOMDocument保存xml時中文出現(xiàn)亂碼問題的解決方案
- php中DOMDocument簡單用法示例代碼(XML創(chuàng)建、添加、刪除、修改)
- PHP XML操作類DOMDocument
- php基于DOMDocument操作頁面元素實例
相關(guān)文章
PHP獲取表單textarea數(shù)據(jù)中的換行問題
閑來無事,在網(wǎng)上看到一篇關(guān)于php表單轉(zhuǎn)換textarea換行符的文章,看完后,根據(jù)以往經(jīng)驗,感覺上這篇文章中的一些信息并不準確...于是便自己親自對php獲取表單數(shù)據(jù)中的換行符問題進行研究2010-09-09php模擬post行為代碼總結(jié)(POST方式不是絕對安全)
GET行為比較簡單,POST比較復雜一些2012-02-02