php生成xml簡(jiǎn)單實(shí)例代碼
Jun 13, 2016 pm 12:20 PM
當(dāng)處理基于XML應(yīng)用程序時(shí),開(kāi)發(fā)者經(jīng)常需要建立XML編碼數(shù)據(jù)結(jié)構(gòu)。例如,Web中基于用戶(hù)輸入的XML狀態(tài)模板,服務(wù)器請(qǐng)求XML語(yǔ)句,以及基于運(yùn)行時(shí)間參數(shù)的客戶(hù)響應(yīng)。
盡管XML數(shù)據(jù)結(jié)構(gòu)的構(gòu)建比較費(fèi)時(shí),但如果使用成熟的PHP DOM應(yīng)用程序接口,一切都會(huì)變得簡(jiǎn)單明了。本文將向你介紹PHP DOM應(yīng)用程序接口的主要功能,演示如何生成一個(gè)正確的XML完整文件并將其保存到磁盤(pán)中。
創(chuàng)建文檔類(lèi)型聲明
一般而言,XML聲明放在文檔頂部。在PHP中聲明十分簡(jiǎn)單:只需實(shí)例化一個(gè)DOM文檔類(lèi)的對(duì)象并賦予它一個(gè)版本號(hào)。查看程序清單A:
程序清單 A
復(fù)制代碼 代碼如下:
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// save and display tree
echo $dom->saveXML();
?>
請(qǐng)注意DOM文檔對(duì)象的saveXML()方法。稍后我再詳細(xì)介紹這一方法,現(xiàn)在你只需要簡(jiǎn)單認(rèn)識(shí)到它用于輸出XML文檔的當(dāng)前快照到一個(gè)文件或?yàn)g覽器。在本例,為增強(qiáng)可讀性,我已經(jīng)將ASCII碼文本直接輸出至瀏覽器。在實(shí)際應(yīng)用中,可將以text/XML頭文件發(fā)送到瀏覽器。
如在瀏覽器中查看輸出,你可看到如下代碼:
添加元素和文本節(jié)點(diǎn)
XML真正強(qiáng)大的功能是來(lái)自其元素與封裝的內(nèi)容。幸運(yùn)的是,一旦你初始化DOM文檔,很多操作變得很簡(jiǎn)單。此過(guò)程包含如下兩步驟:
對(duì)想添加的每一元素或文本節(jié)點(diǎn),通過(guò)元素名或文本內(nèi)容調(diào)用DOM文檔對(duì)象的createElement()或createTextNode()方法。這將創(chuàng)建對(duì)應(yīng)于元素或文本節(jié)點(diǎn)的新對(duì)象。
通過(guò)調(diào)用節(jié)點(diǎn)的appendChild()方法,并把其傳遞給上一步中創(chuàng)建的對(duì)象,并在XML文檔樹(shù)中將元素或文本節(jié)點(diǎn)添加到父節(jié)點(diǎn)。
以下范例將清楚地演示這2步驟,請(qǐng)查看程序清單B。
程序清單 B
復(fù)制代碼 代碼如下:
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
// save and display tree
echo $dom->saveXML();
?>
這 里,我首先創(chuàng)建一個(gè)名字為
復(fù)制代碼 代碼如下:
如果你想添加另外一個(gè)topping,只需創(chuàng)建另外一個(gè)
程序清單C
復(fù)制代碼 代碼如下:
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create another text node
$text = $dom->createTextNode("tomato");
$item->appendChild($text);
// save and display tree
echo $dom->saveXML();
?>
以下是執(zhí)行程序清單C后的輸出:
復(fù)制代碼 代碼如下:
添加屬性
通過(guò)使用屬性,你也可以添加適合的信息到元素。對(duì)于PHP DOM API,添加屬性需要兩步:首先用DOM文檔對(duì)象的createAttribute()方法創(chuàng)建擁有此屬性名字的節(jié)點(diǎn),然后將文檔節(jié)點(diǎn)添加到擁有屬性值的屬性節(jié)點(diǎn)。詳見(jiàn)程序清單D。
程序清單 D
復(fù)制代碼 代碼如下:
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);
// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);
// save and display tree
echo $dom->saveXML();
?>
輸出如下所示:
復(fù)制代碼 代碼如下:
添加CDATA模塊和過(guò)程向?qū)?
雖然不經(jīng)常使用CDATA模塊和過(guò)程向?qū)?,但是通過(guò)調(diào)用DOM文檔對(duì)象的createCDATASection()和createProcessingInstruction()方法, PHP API 也能很好地支持CDATA和過(guò)程向?qū)?,?qǐng)見(jiàn)程序清單E。
程序清單 E
復(fù)制代碼 代碼如下:
// create doctype
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);
// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);
// create CDATA section
$cdata = $dom->createCDATASection(" Customer requests that pizza be sliced into 16 square pieces ");
$root->appendChild($cdata);
// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);
// save and display tree
echo $dom->saveXML();
?>
輸出如下所示:
復(fù)制代碼 代碼如下:
Customer requests that pizza be sliced into 16 square pieces
]]>
保存結(jié)果
一旦已經(jīng)實(shí)現(xiàn)你的目標(biāo),就可以將結(jié)果保存在一個(gè)文件或存儲(chǔ)于PHP的變量。通過(guò)調(diào)用帶有文件名的save()方法可以將結(jié)果保存在文件中,而通過(guò)調(diào)用saveXML()方法可存儲(chǔ)于PHP的變量。請(qǐng)參考以下實(shí)例(程序清單F):
程序清單 F
復(fù)制代碼 代碼如下:
// create doctype
$dom = new DOMDocument("1.0");
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
$dom->formatOutput=true;
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);
// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);
// create CDATA section
$cdata = $dom->createCDATASection(" Customer requests that pizza be
sliced into 16 square pieces ");
$root->appendChild($cdata);
// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);
// save tree to file
$dom->save("order.xml");
// save tree to string
$order = $dom->save("order.xml");
?>
下面是實(shí)際的例子,大家可以測(cè)試下。
xml.php(生成xml)
復(fù)制代碼 代碼如下:
$conn = mysql_connect('localhost', 'root', '123456') or die('Could not connect: ' . mysql_error());
mysql_select_db('vdigital', $conn) or die ('Can\'t use database : ' . mysql_error());
$str = "SELECT id,username FROM `admin` GROUP BY `id` ORDER BY `id` ASC";
$result = mysql_query($str) or die("Invalid query: " . mysql_error());
if($result)
{
$xmlDoc = new DOMDocument();
if(!file_exists("01.xml")){
$xmlstr = "
$xmlDoc->loadXML($xmlstr);
$xmlDoc->save("01.xml");
}
else { $xmlDoc->load("01.xml");}
$Root = $xmlDoc->documentElement;
while ($arr = mysql_fetch_array($result)){
$node1 = $xmlDoc->createElement("id");
$text = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["id"]));
$node1->appendChild($text);
$node2 = $xmlDoc->createElement("name");
$text2 = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["username"]));
$node2->appendChild($text2);
$Root->appendChild($node1);
$Root->appendChild($node2);
$xmlDoc->save("01.xml");
}
}
mysql_close($conn);
?>
test.php(應(yīng)用測(cè)試)
復(fù)制代碼 代碼如下:
$xmlDoc = new DOMDocument();
$xmlDoc->load("http://localhost/xml/xml.php");
$x=$xmlDoc->getElementsByTagName('name');
for ($i=0; $ilength-1; $i++)
{
if(strpos($x->item($i)->nodeValue,"fang")!==false)
{
echo $x->item($i)->parentNode->childNodes->item(1)->nodeValue;
}
}
?>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w
