小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

php 使用PHP的Dom生成xml文件

 明天網(wǎng)吧 2015-07-11

該文舉一個使用php中的dom生成xml文件的簡單例子。假如需要生成一個描述某些博文的xml文件,可以使用下述代碼來生成:

        //定義博文數(shù)據(jù),實際數(shù)據(jù)應(yīng)該從數(shù)據(jù)庫中取出
$articles = array(array('title' => '深入淺出CURL', 'author' => '360weboy'), 
              array('title' => '深入理解execution context', 'author' => 'jack.yin'));

        //構(gòu)建dom document
    $xml = new DOMDocument();
        //格式化輸出
    $xml->formatOutput  = TRUE;

        //設(shè)置xml文檔的編碼為utf8
        $xml->encoding = 'utf8';

        //構(gòu)建文章根節(jié)點
    $root = $xml->createElement('articles');

    if (count($articles) > 0)
    {
                 //遍歷數(shù)組,生成文章子節(jié)點
        foreach($articles as $article)
        {
            //建立文章節(jié)點
                        $a = $xml->createElement('article');

                        //建立title字節(jié)點
            $title = $xml->createElement('title');

                        //建立文本節(jié)點,并且加入到title節(jié)點下

            $title->appendChild($xml->createTextNode($article['title']));

                        //添加title節(jié)點到article節(jié)點下
            $a->appendChild($title);

            $author = $xml->createElement('author');
            $author->appendChild($xml->createTextNode($article['author']));

            $a->appendChild($author);

                        //添加article節(jié)點到根節(jié)點下
            $root->appendChild($a);
        }
    }

        //添加根節(jié)點到xml文檔下
    $xml->appendChild($root);

        //設(shè)置charset為utf-8,不然瀏覽器會顯示中文為亂碼
        header('Content-Type: text/html;charset=UTF-8');

        //保存xml文檔到artciles.xml
    if ($xml->save('articles.xml') !== FALSE)
    {
        echo 'articles.xml已經(jīng)生成保存!';
    }
    else
    {
        echo 'articles.xml生成失敗';
    }

上述代碼生成的xml文檔如下:

<?xml version="1.0"?>
<articles>
  <article>
    <title><![CDATA[深入淺出CURL]]></title>
    <author>360weboy</author>
  </article>
  <article>
    <title><![CDATA[深入理解execution context]]></title>
    <author>jack.yin</author>
  </article>
</articles>

總結(jié): 當然,讀取xml文檔的方式也差不多。使用dom來處理一些小型xml文檔還是比較不錯的,如果你熟悉javascript的話,相信dom這種方式對你來說還是很好理解的。但是,由于使用這種方式的話,php需要將這個文檔讀入內(nèi)存中,構(gòu)建一顆dom樹,所以,如果處理大型xml文檔的話,是不太合適的,因為太消耗內(nèi)存了! 其它方法請參考手冊 – http:///manual/en/class.domdocument.php

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多