分享

php 使用PHP的Dom生成xml文件

 明天网吧 2015-07-11

该文举一个使用php中的dom生成xml文件的简单例子。假如需要生成一个描述某些博文的xml文件,可以使用下述代码来生成:

        //定义博文数据,实际数据应该从数据库中取出
$articles = array(array('title' => '深入浅出CURL', 'author' => '360weboy'), 
              array('title' => '深入理解execution context', 'author' => 'jack.yin'));

        //构建dom document
    $xml = new DOMDocument();
        //格式化输出
    $xml->formatOutput  = TRUE;

        //设置xml文档的编码为utf8
        $xml->encoding = 'utf8';

        //构建文章根节点
    $root = $xml->createElement('articles');

    if (count($articles) > 0)
    {
                 //遍历数组,生成文章子节点
        foreach($articles as $article)
        {
            //建立文章节点
                        $a = $xml->createElement('article');

                        //建立title字节点
            $title = $xml->createElement('title');

                        //建立文本节点,并且加入到title节点下

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

                        //添加title节点到article节点下
            $a->appendChild($title);

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

            $a->appendChild($author);

                        //添加article节点到根节点下
            $root->appendChild($a);
        }
    }

        //添加根节点到xml文档下
    $xml->appendChild($root);

        //设置charset为utf-8,不然浏览器会显示中文为乱码
        header('Content-Type: text/html;charset=UTF-8');

        //保存xml文档到artciles.xml
    if ($xml->save('articles.xml') !== FALSE)
    {
        echo 'articles.xml已经生成保存!';
    }
    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>

总结: 当然,读取xml文档的方式也差不多。使用dom来处理一些小型xml文档还是比较不错的,如果你熟悉javascript的话,相信dom这种方式对你来说还是很好理解的。但是,由于使用这种方式的话,php需要将这个文档读入内存中,构建一颗dom树,所以,如果处理大型xml文档的话,是不太合适的,因为太消耗内存了! 其它方法请参考手册 – http:///manual/en/class.domdocument.php

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多