对于PHP语言的初学者来说,PHP DOM-XML还是比较陌生的,希望朋友们能通过这篇文章具体了解这方面的知识,以加深对PHP的了解程度。

我们在创建XML文件并对其进行解析时,通常都会用到PHP DOM-XML。那么如何才能正确的使用它来实现这一功能呢?下面我们就来仔细看下它的应用方法。#t#

如何正确使用PHP DOM-XML创建XML文件  PHP DOM-XML 第1张

PHP DOM-XML的应用代码示例:

  1. <?PHP
  2. /**
  3. *Topic:CreateandparseXMLfilesusingPHPDOM-XML
  4. *Source:http://www.php.net/DOM-XML
  5. *Reference:http://www.zugeschaut-und-mitgebaut.de/php/extension.domxml.html
  6. *Author:urs@circle.ch,16-1-2001
  7. *
  8. */
  9. //使用PHPDOM-XML创建和解析XML文件
  10. //创建XML文档对象;以后的处理过程将在此基础上进行
  11. doc=new_xmldoc("1.0");
  12. //创建根节点,并设置一个属性
  13. root=$doc->add_root("faq");
  14. $root->setattr("page","32");
  15. //子节点
  16. one=$root->new_child("question","");
  17. //为子节点设置属性
  18. $one->setattr("number","1");
  19. //question也创建子节点,并且给它赋值
  20. $one->new_child("text","1.Wheretogetlibxml-2.0.0?");
  21. $one->new_child("answer","Youcandownloadthelatest
  22. releaseoflibxmleitherasasourcearchiveor
  23. RPMpackagefromhttp://www.xmlsoft.org.
  24. Thecurrentversionislibxml2-2.2.1.");
  25. two=$root->new_child("question","");
  26. $two->setattr("number","2");
  27. $two->new_child("text","2.HowtoconfigurePHP4?");
  28. //创建一个不直接赋值的节点
  29. twoone=$two->new_child("answer","");
  30. //然后给它单独赋值
  31. $twoone->set_content("DIRisthelibxmlinstalldirectory
  32. (ifyoujustuse--with-domitdefaults
  33. to/usr),Ineededtouse--with-dom=/usr/local");
  34. three=$root->new_child("question","");
  35. $three->setattr("number","7");
  36. $three->new_child("text","7.HowtouseDOMXMLfunction?");
  37. $three->new_child("answer","Readthisdocumentsourcefor
  38. asimpleexample.");
  39. //输出到Browser
  40. print("<pre>".htmlspecialchars($doc->dumpmem())."</pre>");
  41. //writetofile
  42. //写回到文件
  43. fp=fopen("test_dom.xml","w+");
  44. fwrite($fp,$doc->dumpmem(),strlen($doc->dumpmem()));
  45. fclose($fp);
  46. //现在使用xpath从XML文档中得到内容
  47. doc=xmldoc(join("",file("test_dom.xml")));
  48. ctx=xpath_new_context($doc);
  49. //所有对象
  50. foo=xpath_eval($ctx,"//child::*");
  51. print_r($foo);
  52. print("<br/><br/>");
  53. //textnode对象
  54. foo=xpath_eval($ctx,"//text");
  55. print_r($foo);
  56. print("<br/><br/>");
  57. //***个textnode对象
  58. foo=xpath_eval($ctx,"//text[1]");
  59. print_r($foo);
  60. print("<br/><br/>");
  61. //第二个textnode对象
  62. foo=xpath_eval($ctx,"//text[2]");
  63. print_r($foo);
  64. print("<br/><br/>");
  65. //第三个answer对象
  66. foo=xpath_eval($ctx,"//answer[3]");
  67. print_r($foo);
  68. print("<br/><br/>");
  69. //第三个textnode的类型,名称和内容
  70. foo=xpath_eval($ctx,"//text[3]");
  71. tmp=$foo->nodeset;
  72. print_r($tmp);
  73. print("<br/>");
  74. print($tmp[0]->type).";";
  75. print($tmp[0]->name).";";
  76. print($tmp[0]->content);
  77. ?>

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

转载请说明出处
知优网 » 如何正确使用PHP DOM-XML创建XML文件

发表评论

您需要后才能发表评论