对于PHP语言的初学者来说,PHP DOM-XML还是比较陌生的,希望朋友们能通过这篇文章具体了解这方面的知识,以加深对PHP的了解程度。
我们在创建XML文件并对其进行解析时,通常都会用到PHP DOM-XML。那么如何才能正确的使用它来实现这一功能呢?下面我们就来仔细看下它的应用方法。#t#
PHP DOM-XML的应用代码示例:
- <?PHP
- /**
- *Topic:CreateandparseXMLfilesusingPHPDOM-XML
- *Source:http://www.php.net/DOM-XML
- *Reference:http://www.zugeschaut-und-mitgebaut.de/php/extension.domxml.html
- *Author:urs@circle.ch,16-1-2001
- *
- */
- //使用PHPDOM-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.Wheretogetlibxml-2.0.0?");
- $one->new_child("answer","Youcandownloadthelatest
- releaseoflibxmleitherasasourcearchiveor
- RPMpackagefromhttp://www.xmlsoft.org.
- Thecurrentversionislibxml2-2.2.1.");
- $two=$root->new_child("question","");
- $two->setattr("number","2");
- $two->new_child("text","2.HowtoconfigurePHP4?");
- //创建一个不直接赋值的节点
- $twoone=$two->new_child("answer","");
- //然后给它单独赋值
- $twoone->set_content("DIRisthelibxmlinstalldirectory
- (ifyoujustuse--with-domitdefaults
- to/usr),Ineededtouse--with-dom=/usr/local");
- $three=$root->new_child("question","");
- $three->setattr("number","7");
- $three->new_child("text","7.HowtouseDOMXMLfunction?");
- $three->new_child("answer","Readthisdocumentsourcefor
- asimpleexample.");
- //输出到Browser
- print("<pre>".htmlspecialchars($doc->dumpmem())."</pre>");
- //writetofile
- //写回到文件
- $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/>");
- //textnode对象
- $foo=xpath_eval($ctx,"//text");
- print_r($foo);
- print("<br/><br/>");
- //***个textnode对象
- $foo=xpath_eval($ctx,"//text[1]");
- print_r($foo);
- print("<br/><br/>");
- //第二个textnode对象
- $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/>");
- //第三个textnode的类型,名称和内容
- $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-XML只能在PHPPHP4.0.x + linux上运行
转载请说明出处
知优网 » 如何正确使用PHP DOM-XML创建XML文件
知优网 » 如何正确使用PHP DOM-XML创建XML文件