如何正確使用PHP DOM-XML創(chuàng)建XML文件
作者:佚名
對(duì)于PHP語言的初學(xué)者來說,PHP DOM-XML還是比較陌生的,希望朋友們能通過這篇文章具體了解這方面的知識(shí),以加深對(duì)PHP的了解程度。
我們?cè)趧?chuàng)建XML文件并對(duì)其進(jìn)行解析時(shí),通常都會(huì)用到PHP DOM-XML。那么如何才能正確的使用它來實(shí)現(xiàn)這一功能呢?下面我們就來仔細(xì)看下它的應(yīng)用方法。#t#
PHP DOM-XML的應(yīng)用代碼示例:
- < ?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創(chuàng)建和解析XML文件
- //創(chuàng)建XML文檔對(duì)象;以后的處理過程將在此基礎(chǔ)上進(jìn)行
- $doc = new_xmldoc("1.0" );
- //創(chuàng)建根節(jié)點(diǎn),并設(shè)置一個(gè)屬性
- $root = $doc->add_root("faq" );
- $root->setattr("page", "32" );
- //子節(jié)點(diǎn)
- $one = $root->new_child("question", "");
- //為子節(jié)點(diǎn)設(shè)置屬性
- $one->setattr("number", "1");
- //question也創(chuàng)建子節(jié)點(diǎn),并且給它賦值
- $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?" );
- // 創(chuàng)建一個(gè)不直接賦值的節(jié)點(diǎn)
- $twoone = $two->new_child("answer", "");
- // 然后給它單獨(dú)賦值
- $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);
- //現(xiàn)在使用xpath從XML文檔中得到內(nèi)容
- $doc = xmldoc(join("", file("test_dom.xml")) );
- $ctx = xpath_new_context($doc );
- //所有對(duì)象
- $foo = xpath_eval($ctx, "//child::*");
- print_r($foo);
- print("< br/>< br/>");
- //text node 對(duì)象
- $foo = xpath_eval($ctx, "//text");
- print_r($foo);
- print("< br/>< br/>");
- // ***個(gè)text node對(duì)象
- $foo = xpath_eval($ctx, "//text[1]");
- print_r($foo);
- print("< br/>< br/>");
- // 第二個(gè)text node對(duì)象
- $foo = xpath_eval($ctx, "//text[2]");
- print_r($foo);
- print("< br/>< br/>");
- // 第三個(gè)answer對(duì)象
- $foo = xpath_eval($ctx, "//answer[3]");
- print_r($foo);
- print("< br/>< br/>");
- //第三個(gè)text node的類型,名稱和內(nèi)容
- $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上運(yùn)行
責(zé)任編輯:曹凱
來源:
王朝網(wǎng)絡(luò)