溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php生成xml文件的方法

發(fā)布時間:2020-06-11 11:31:08 來源:億速云 閱讀:333 作者:Leah 欄目:編程語言

本篇文章展示了php生成xml文件的具體操作,代碼簡明扼要容易理解,如果在日常工作遇到這個疑問。希望大家通過這篇文章,找到解決疑問的辦法。

使用PHP DOMDocument創(chuàng)建動態(tài)XML文件

當(dāng)處理基于XML應(yīng)用程序時,開發(fā)者經(jīng)常需要建立XML編碼數(shù)據(jù)結(jié)構(gòu)。例如,Web中基于用戶輸入的XML狀態(tài)模板,服務(wù)器請求XML語句,以及基于運行時間參數(shù)的客戶響應(yīng)。
盡管XML數(shù)據(jù)結(jié)構(gòu)的構(gòu)建比較費時,但如果使用成熟的PHP DOM應(yīng)用程序接口,一切都會變得簡單明了。本文將向你介紹PHP DOM應(yīng)用程序接口的主要功能,演示如何生成一個正確的XML完整文件并將其保存到磁盤中。
創(chuàng)建文檔類型聲明
一般而言,XML聲明放在文檔頂部。在PHP中聲明十分簡單:只需實例化一個DOM文檔類的對象并賦予它一個版本號。查看程序清單A:
程序清單 A

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain"); 
    // save and display tree 
    echo $dom->saveXML(); 
?>

請注意DOM文檔對象的saveXML()方法。稍后我再詳細介紹這一方法,現(xiàn)在你只需要簡單認識到它用于輸出XML文檔的當(dāng)前快照到一個文件或瀏覽器。在本例,為增強可讀性,我已經(jīng)將ASCII碼文本直接輸出至瀏覽器。在實際應(yīng)用中,可將以text/XML頭文件發(fā)送到瀏覽器。


如在瀏覽器中查看輸出,你可看到如下代碼:
<?xml version="1.0"?>
添加元素和文本節(jié)點
XML真正強大的功能是來自其元素與封裝的內(nèi)容。幸運的是,一旦你初始化DOM文檔,很多操作變得很簡單。此過程包含如下兩步驟:
對想添加的每一元素或文本節(jié)點,通過元素名或文本內(nèi)容調(diào)用DOM文檔對象的createElement()或createTextNode()方法。這將創(chuàng)建對應(yīng)于元素或文本節(jié)點的新對象。
通過調(diào)用節(jié)點的appendChild()方法,并把其傳遞給上一步中創(chuàng)建的對象,并在XML文檔樹中將元素或文本節(jié)點添加到父節(jié)點。
以下范例將清楚地演示這2步驟,請查看程序清單B。
程序清單 B

<?php 
    // 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)建一個名字為<toppings>的根元素,并使它歸于XML頭文件中。然后,我建立名為<item>的元素并使它 歸于根元素。最后,我又創(chuàng)建一個值為“pepperoni”的文本節(jié)點并使它歸于<item>元素。最終結(jié)果如下:

<?xml version="1.0"?> 
<toppings> 
    <item>pepperoni</item> 
</toppings>

如果你想添加另外一個topping,只需創(chuàng)建另外一個<item>并添加不同的內(nèi)容,如程序清單C所示。
程序清單C

<?php 
    // 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后的輸出:

<?xml version="1.0"?> 
<toppings> 
    <item>pepperoni</item> 
    <item>tomato</item> 
</toppings>

添加屬性
通過使用屬性,你也可以添加適合的信息到元素。對于PHP DOM API,添加屬性需要兩步:首先用DOM文檔對象的createAttribute()方法創(chuàng)建擁有此屬性名字的節(jié)點,然后將文檔節(jié)點添加到擁有屬性值的屬性節(jié)點。詳見程序清單D。
程序清單 D

<?php 
    // 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(); 
?>

輸出如下所示:

<?xml version="1.0"?> 
<toppings> 
    <item price="4">pepperoni</item> 
</toppings>

添加CDATA模塊和過程向?qū)?
雖然不經(jīng)常使用CDATA模塊和過程向?qū)В峭ㄟ^調(diào)用DOM文檔對象的createCDATASection()和createProcessingInstruction()方法, PHP API 也能很好地支持CDATA和過程向?qū)?,請見程序清單E。
程序清單 E

<?php 
    // 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(); 
?>

輸出如下所示:

<?xml version="1.0"?> 
<toppings> 
<item price="4">pepperoni</item> 
<![CDATA[ 
Customer requests that pizza be sliced into 16 square pieces 
]]> 
<?pizza bake()?> 
</toppings>

保存結(jié)果
一旦已經(jīng)實現(xiàn)你的目標(biāo),就可以將結(jié)果保存在一個文件或存儲于PHP的變量。通過調(diào)用帶有文件名的save()方法可以將結(jié)果保存在文件中,而通過調(diào)用saveXML()方法可存儲于PHP的變量。請參考以下實例(程序清單F):
程序清單 F

<?php 
    // 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"); 
?>

下面是實際的例子,大家可以測試下。
xml.php(生成xml)

<? 
    $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 = "<?xml version='1.0' encoding='utf-8' ?><message></message>"; 
            $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); 
?>

關(guān)于php生成xml文件的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI