主頁 > 知識(shí)庫 > PHP創(chuàng)建XML的方法示例【基于DOMDocument類及SimpleXMLElement類】

PHP創(chuàng)建XML的方法示例【基于DOMDocument類及SimpleXMLElement類】

熱門標(biāo)簽:電子圍欄 團(tuán)購網(wǎng)站 Linux服務(wù)器 阿里云 Mysql連接數(shù)設(shè)置 銀行業(yè)務(wù) 科大訊飛語音識(shí)別系統(tǒng) 服務(wù)器配置

本文實(shí)例講述了PHP創(chuàng)建XML的方法。分享給大家供大家參考,具體如下:

使用DOMDocument類創(chuàng)建xml

config.php

?php
$doc = new DOMDocument('1.0','utf-8');
$doc->formatOutput = true;
//創(chuàng)建標(biāo)簽
$mysql = $doc->createElement("mysql");
$host = $doc->createElement("host");
$username = $doc->createElement("username");
$password = $doc->createElement("password");
$database = $doc->createElement("database");
//創(chuàng)建標(biāo)簽內(nèi)容
$hostval = $doc->createTextNode("127.0.0.1");
$usernameval = $doc->createTextNode("root");
$passwordval = $doc->createTextNode("1234");
$databaseval = $doc->createTextNode("test");
//綁定標(biāo)簽和內(nèi)容
$host->appendChild($hostval);
$username->appendChild($usernameval);
$password->appendChild($passwordval);
$database->appendChild($databaseval);
//關(guān)聯(lián)標(biāo)簽之間的關(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è)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • PHP中使用DOMDocument來處理HTML、XML文檔的示例
  • PHP讀取XML文件的方法實(shí)例總結(jié)【DOMDocument及simplexml方法】
  • PHP基于DOMDocument解析和生成xml的方法分析
  • 如何解決php domdocument找不到的問題

標(biāo)簽:大理 衡水 蚌埠 棗莊 萍鄉(xiāng) 衢州 廣元 江蘇

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP創(chuàng)建XML的方法示例【基于DOMDocument類及SimpleXMLElement類】》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266