使用PHP DOM-XML建立和解析XML檔案 (轉)

worldblog發表於2007-12-09
使用PHP DOM-XML建立和解析XML檔案 (轉)[@more@]

 
  /**
  * Topic:  Create and parse files using PHP -XML
  * :  /domxml">
  * Reference: 
  * Author:  to:urs@circle.ch">urs@circle.ch, 16-1-2001
  *
  */ 
// 使用PHP DOM-XML建立和解析XML

  //建立XML文件;以後的處理過程將在此基礎上進行
  $doc = new_xmldoc("1.0" ); 

  //建立根節點,並設定一個屬性
  $ = $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 the latest
  release of libxml  either as a source archive or
  RPM package from .
  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 ?" ); 
  // 建立一個不直接賦值的節點
  $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("

".htmlspecialchars($doc->dumpmem() )."
" ); 

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

  // ------------------------------------------------------
  //現在使用從XML文件中得到內容
 
  $doc = xmldoc(join("", file("test_dom.xml")) ); 
  $ctx = xpath_new_context($doc ); 

  //所有物件
  $foo = xpath_eval($ctx, "//child::*"); 
  print_r($foo); 
  print("

"); 
  //text node 物件
  $foo = xpath_eval($ctx, "//text"); 
  print_r($foo); 
  print("

"); 
  // 第一個text node物件
  $foo = xpath_eval($ctx, "//text[1]"); 
  print_r($foo); 
  print("

"); 
  // 第二個text node物件
  $foo = xpath_eval($ctx, "//text[2]"); 
  print_r($foo); 
  print("

"); 
  // 第三個answer物件
  $foo = xpath_eval($ctx, "//answer[3]"); 
  print_r($foo); 
  print("

"); 

  //第三個text node的型別,名稱和內容
  $foo = xpath_eval($ctx, "//text[3]"); 
  $tmp = $foo->nodeset; 
  print_r($tmp); 
  print("
"); 
  print($tmp[0]->type) . "; "; 
  print($tmp[0]->name) . "; "; 
  print($tmp[0]->content); 

?> 

需要說明,PHP DOM 只能在PHP  PHP4.0.x + 上執行

PHPDOM類庫請到.com/download">下載


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-990353/,如需轉載,請註明出處,否則將追究法律責任。

相關文章