xml相關處理

<?xml version="1.0" encoding="utf-8"?>  
<phplamp>  
 <post>  
  <title id="1">PHP XML處理介紹一</title>  
  <details>詳細內容一</details>  
 </post>  

 <post>  
  <title id="2">PHP XML處理介紹二</title>  
  <details>詳細內容二</details>  
 </post>  

 <post>  
  <title id="3">PHP XML處理介紹三</title>  
  <details>詳細內容三</details>  
 </post>  
</phplamp>

 

 

<?php  
 // 首先要建一個DOMDocument對象  
 $xml = new DOMDocument();  
 
 // 加載Xml文件  
 $xml->load("me.xml");  
 
 // 獲取所有的post標籤  
 $postDom = $xml->getElementsByTagName("post");  
 
 // 循環遍歷post標籤  
 foreach($postDom as $post){  
  // 獲取Title標籤Node  
  $title = $post->getElementsByTagName("title");  
 
  /**  
  * 要獲取Title標籤的Id屬性要分兩部走  
  * 1. 獲取title中所有屬性的
  列表也就是$title->item(0)->attributes  
  * 2. 獲取title中id的屬性,
  因爲其在第一位所以用item(0)  
  *  
  * 小提示:  
  * 若取屬性的值可以用item(*)->nodeValue  
  * 若取屬性的標籤可以用item(*)->nodeName  
  * 若取屬性的類型可以用item(*)->nodeType  
  */  
  echo "Id: " . $title->item(0)->attributes->item(0)->nodeValue . "<br />";  
  echo "Title: " . $title->item(0)->nodeValue . "<br />";  
  echo "Details: " . $post->getElementsByTagName("details")->item(0)->nodeValue . "<br /><br />";  
 }  
?> 

 

 

 

<?php
$doc = new DOMDocument; 
$doc->load('book.xml'); 
$book = $doc->documentElement; 
$airline = $book->getElementsByTagName('airline'); 
//echo $air_info->getAttribute('ret_value');
foreach($airline as $c) 

  echo $c->getAttribute('line_number'),'<br/>';
  //echo $c->getAttribute('company'),'<br/>';
  /* 其它屬性 */
  $childnodes = $c->getElementsByTagName('c');
  foreach($childnodes as $childc){
   echo $childc->getAttribute('b'),'<br/>';
   /* 其它屬性 $childc->getAttribute('d')*/
  }
}
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章