欢迎光临
我们一直在努力

使用PHP DOM-XML创建和解析XML文件-PHP教程,XML应用

建站超值云服务器,限时71元/月

<?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: urs@circle.ch, 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 只能在php php4.0.x + linux上运行

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 使用PHP DOM-XML创建和解析XML文件-PHP教程,XML应用
分享到: 更多 (0)

相关推荐

  • 暂无文章