php DOMDocument 创建,加载,解析xml文档代码

 更新时间:2016年11月25日 16:55  点击:1527
下面这主要是针对于DOMDocument对于xml的简单操作来举例说明了, 我们主要是讲到了关于xml的创建,加载,解析xml哦。
 代码如下 复制代码

$xml_str = "<?xml version='1.0'?>";
$xml_str .= "<books>";
$xml_str .= "<book>";
$xml_str .= "<title>harry potter</title>";
$xml_str .= "<author>j.k.rowling</author>";
$xml_str .= "<publisher>warner bros.</publisher>";
$xml_str .= "<price>39.0</price>";
$xml_str .= "</book>";
$xml_str .= "</books>";

$dom = new domdocument;
$dom->loadxml($xml_str);

echo $dom->savexml();
$dom->save("test.xml");

//domdocument 加载xml文档

$dom = new domdocument;

$dom->load('17-1.xml');
$root = $dom->documentelement;


//解析xml文档

 代码如下 复制代码

$doc = new domdocument();
$doc->load("17-1.xml");

$books = $doc->getelementsbytagname("book");
foreach($books as $book)
{
    $authors = $book->getelementsbytagname("author");
    $author = $authors->item(0)->nodevalue;
   
    $publishers = $book->getelementsbytagname("publisher");
    $publisher = $publishers->item(0)->nodevalue;
   
    $titles = $book->getelementsbytagname("title");
    $title = $titles->item(0)->nodevalue;
   
    $prices = $book->getelementsbytagname("price");
    $price = $prices->item(0)->nodevalue;
   
    echo "$title - $author - $publisher - $price";
    echo "<br/>";
    echo "<br/>";
}

/*
17-1.xml

 代码如下 复制代码
<?xml version="1.0" encoding="gb2312"?>
<books>
    <book>
        <title>learning php5</title>
        <author>david</author>
        <publisher>white water press</publisher>
        <price>29.90</price>
    </book>
    <book>
        <title>learning xml</title>
        <author>jeffson</author>
        <publisher>white water press</publisher>
        <price>50.79</price>
    </book>
    <book>
        <title>using perl</title>
        <author>lucas</author>
        <publisher>white water press</publisher>
        <price>17.00</price>
    </book>
    <book>
        <title>windows networks</title>
        <author>paul</author>
        <publisher>white water press</publisher>
        <price>32.99</price>
    </book>
    <book>
        <title>fly leaf</title>
        <author>jenny</author>
        <publisher>white water press</publisher>
        <price>19.50</price>
    </book>
</books>

*/
?>

本文章为你提供一款php xml读取类,很简单的一个xml分析类了,它可读取指它xml文档,并且输出或取得指定节点的xml数据哦。
 代码如下 复制代码
class dom
{
  protected $_dom = null;
  
  public function __construct($xmlfile = '',$ver = '',$encoding = '')
  {
    $this -> _dom = ($ver && $encoding)? new domdocument($ver,$encoding):new domdocument();
    $xml = !$xmlfile?file_get_contents('php://input'):file_get_contents($xmlfile);
    $this -> _dom -> loadxml($xml);
  }
  
  public function getvalue($nodename)
  {
    $nodes = $this -> _dom -> getelementsbytagname($nodename);
    return null !== $nodes -> item(0)?$nodes -> item(0) -> nodevalue:false;
  }
}


//本xml类代码是利用了php domdocument来解析xml文档  ?>

//photo_xml类,继承php5的domdocument类

 代码如下 复制代码
class photo_xml extends domdocument
{
    private $root;    //属性
    //构造函数
    public function __construct()
    {
        parent::__construct();
        if (!file_exists("sitecontent.xml"))
        {
            $xmlstr = "<?xml version='1.0' encoding='gb2312'?><bookpages></bookpages>";
            $this->loadxml($xmlstr);
            $this->save("sitecontent.xml");
        }
        else
        {
            $this->load("sitecontent.xml");
        }
    }
   
    //添加图片
    public function addphoto($address,$note)
    {
        $root = $this->documentelement;
        //获取留言消息
       
        $node_address = $this->createelement("page"); //添加<page>标签
        $type=$this->createattribute("src");
        $node_address->appendchild($type);    //添加src的属性
        $type_text=$this->createtextnode($address);
        $type->appendchild($type_text);
        $text= $this->createtextnode(iconv("gb2312","utf-8",$note));
        $node_address->appendchild($text);
        //加入到根结点下
        $root->appendchild($this->appendchild($node_address));
        $this->save("sitecontent.xml");
    }
}

?>

<?php

 代码如下 复制代码
$photo_xml=new photo_xml();
$photo_xml->addphoto('./www.111cn.net/p31.jpg','page31');


?>

<?
if (defined('_class_rss_php教程')) return;
define('_class_rss_php教程',1);
/**
 
 *  使用说明:
 *  $rss = new rss('redfox','http://111cn.net/',"redfox's blog");
 *  $rss->additem('rss class',"http://www.111cn.net","xxx",date());
 *  $rss->additem(...);
 *  $rss->savetofile(...);
 */

 

 代码如下 复制代码

class rss {
   //public
   $rss_ver = "2.0";
   $channel_title = '';
   $channel_link = '';
   $channel_description = '';
   $language = 'zh_cn';
   $copyright = '';
   $webmaster = '';
   $pubdate = '';
   $lastbuilddate = '';
   $generator = 'redfox rss generator';


   $content = '';
   $items = array();


   function rss($title, $link, $description) {
       $this->channel_title = $title;
       $this->channel_link = $link;
       $this->channel_description = $description;
       $this->pubdate = date('y-m-d h:i:s',time());
       $this->lastbuilddate = date('y-m-d h:i:s',time());
   }


   function additem($title, $link, $description ,$pubdate) {
       $this->items[] = array('titile' => $title ,
                        'link' => $link,
                        'description' => $description,
                        'pubdate' => $pubdate);
   }


   function buildrss() {
       $s = "<!--l version="1.0" encoding="gb2312"--> ";
       // start channel
       $s .= " ";
       $s .= " "
       $s .= "<link />{$this->channel_link} ";
       $s .= "{$this->channel_description} ";
       $s .= "{$this->language} ";
       if (!empty($this->copyright)) {
          $s .= "{$this->copyright} ";
       }
       if (!empty($this->webmaster)) {
          $s .= "{$this->webmaster} ";
       }
       if (!empty($this->pubdate)) {
          $s .= "{$this->pubdate} ";
       }


       if (!empty($this->lastbuilddate)) {
          $s .= "{$this->lastbuilddate} ";
       }


       if (!empty($this->generator)) {
          $s .= "{$this->generator} ";
       }
     
       // start items
       for ($i=0;$iitems),$i++) {
           $s .= " ";
           $s .= " ";
           $s .= "<link />{$this->items[$i]['link']} ";
           $s .= "<!--data[{$thi-->items[$i]['description']}]]> ";
           $s .= "{$this->items[$i]['pubdate']} ";         
           $s .= " ";
       }
    
      // close channel
      $s .= " ";
      $this->content = $s;
   }


   function show() {
       if (empty($this->content)) $this->buildrss();
       header('content-type:text/xml');
       echo($this->content);
   }


   function savetofile($fname) {
       if (empty($this->content)) $this->buildrss();
       $handle = fopen($fname, 'wb');
       if ($handle === false)  return false;
       fwrite($handle, $this->content);
       fclose($handle);
   }
}


?>
同时也可以用网页特效来解析xml文档

$doc = new domdocument('1.0');
// we want a nice output
$doc->formatoutput = true;

 代码如下 复制代码

$root = $doc->createelement('book');
$root = $doc->appendchild($root);

$title = $doc->createelement('title');$title = $root->appendchild($title);

$text = $doc->createtextnode('this is the title');
$text = $title->appendchild($text);

echo "retrieving all the document: ";
echo $doc->savexml() . " ";

echo "retrieving only the title part: ";
echo $doc->savexml($title);

[!--infotagslink--]

相关文章

  • 用js的document.write输出的广告无阻塞加载的方法

    一、广告代码分析很多第三方的广告系统都是使用document.write来加载广告,如下面的一个javascript的广告链接。复制代码 代码如下:<script type="text/javascript" src="http://gg.5173.com/adpolestar/5173/;ap=2EBE5...2014-06-07
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13
  • vue项目,代码提交至码云,iconfont的用法说明

    这篇文章主要介绍了vue项目,代码提交至码云,iconfont的用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-30
  • IDEA插件之快速删除Java代码中的注释

    这篇文章主要介绍了IDEA插件之快速删除Java代码中的注释,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-18