当前位置: 首页 > 图文教程 > XML家族 > XML > 使用PHP DOM-XML创建和解析XML文件

XML
数据库生成xml的简单方法
XML教程:通过一个例子来学习XML的语法
XML教程:XML有哪些用途?
XML教程:什么是XML及XML和HTML的区别
初学XML的基础知识(认识XML的作用)
学习XML关于图像超链接的制作
Microsoft的XMLHTTP对象介绍
了解WEB页面工具语言XML(六)展望
了解WEB页面工具语言XML(五)好处
用XML将机器内码转换为人们容易理解的信息
将XML数据转换成HTM
(javascript+asp)XML、XSL转换输出HTML
在XML模式中扩展枚举列表
XML入门教程:XML名称空间
XML入门教程:属性声明
XML入门教程:实体
XML入门教程:元素声明
XML入门教程:文档类型声明
xml入门教程:XML是什么
WAP教程(11):WAP论坛和开放移动联盟与论坛

使用PHP DOM-XML创建和解析XML文件


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 70 ::
收藏到网摘: n/a

使用PHP DOM-XML创建和解析XML文件
<?php
/**
* Topic: Create and parse XML files using PHP DOM-XML
* Source:http://www.php.net/domxml
* Reference: http://www.zugeschaut-und-mitgebaut.de/php/extension.domxml.html
* Author:[email protected], 16-1-2001
*
*/
// 使用PHP DOM-XML创建和解析XML文件

//创建XML文档对象;以后的处理过程将在此基础上进行
$doc = new_xmldoc("1.0" );

//创建根节点,并设置一个属性
$root = $doc->add_root("faq" );
$root->setattr("page", "32" );

//子节点
$one = $root->new_child("question", "");
//为子节点设置属性
$one->setattr("number", "1");
//question也创建子节点,并且给它赋值
$one->new_child("text", "1. Where to get libxml-2.0.0?");
$one->new_child("answer", "You can download the latest
release of libxml either as a source archive or
RPM package from http://www.xmlsoft.org.
The current version is libxml2-2.2.1." );

$two = $root->new_child("question", "" );
$two->setattr("number", "2");
$two->new_child("text", "2. How to configure PHP4?" );
// 创建一个不直接赋值的节点
$twoone = $two->new_child("answer", "");
// 然后给它单独赋值
$twoone->set_content("DIR is the libxml install directory
(if you just use --with-dom it defaults
to /usr), I needed to use --with-dom=/usr/local" );

$three = $root->new_child("question", "" );
$three->setattr("number", "7" );
$three->new_child("text", "7. How to use DOM XML function ?" );
$three->new_child("answer", "Read this document source for
a simple example." );

//输出到Browser
print("<pre>".htmlspecialchars($doc->dumpmem() )."</pre>" );

// write to file
//写回到文件
$fp = fopen("test_dom.xml", "w+" );
fwrite($fp, $doc->dumpmem(), strlen($doc->dumpmem() ));
fclose($fp);

// ------------------------------------------------------
//现在使用xpath从XML文档中得到内容

$doc = xmldoc(join("", file("test_dom.xml")) );
$ctx = xpath_new_context($doc );

//所有对象
$foo = xpath_eval($ctx, "//child::*");
print_r($foo);
print("<br/><br/>");
//text node 对象
$foo = xpath_eval($ctx, "//text");
print_r($foo);
print("<br/><br/>");
// 第一个text node对象
$foo = xpath_eval($ctx, "//text[1]");
print_r($foo);
print("<br/><br/>");
// 第二个text node对象
$foo = xpath_eval($ctx, "//text[2]");
print_r($foo);
print("<br/><br/>");
// 第三个answer对象
$foo = xpath_eval($ctx, "//answer[3]");
print_r($foo);
print("<br/><br/>");

//第三个text node的类型,名称和内容
$foo = xpath_eval($ctx, "//text[3]");
$tmp = $foo->nodeset;
print_r($tmp);
print("<br/>");
print($tmp[0]->type) . "; ";
print($tmp[0]->name) . "; ";
print($tmp[0]->content);

?>

需要说明,PHP DOM 只能在PHPPHP4.0.x + linux上运行

PHPDOM类库请到http://www.zend.com/download下载。