2012-01-05 91 views
0

我正在使用simplexml_load_string函數來處理xml字符串。PHP XML處理,讀取屬性

以下是xml字符串。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
    <metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#"  
    xmlns:ext="http://musicbrainz.org/ns/ext#-2.0"> 
    <artist-list offset="0" count="1422"> 
     <artist ext:score="100" type="Person" id="72c536dc-7137-4477-a521-567eeb840fa8"> 
     <name>Bob Dylan</name> 
     <sort-name>Dylan, Bob</sort-name> 
     <gender>male</gender><country>US</country> 
     <life-span><begin>1941-05-24</begin></life-span> 
    </artist> 
    </artist-list> 
    </metadata> 

當函數返回時,我得到下面的數組。 我想要讀取藝術家ext:score =「value」,但它不會被返回,我將如何獲取標籤的這個屬性?

SimpleXMLElement Object 
(
    [artist-list] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [offset] => 0 
       [count] => 1422 
      ) 

     [artist] => Array 
      (
       [0] => SimpleXMLElement Object 
        (
         [@attributes] => Array 
          (
           [type] => Person 
           [id] => 72c536dc-7137-4477-a521-567eeb840fa8 
          ) 

         [name] => Bob Dylan 
         [sort-name] => Dylan, Bob 
         [gender] => male 
         [country] => US 
         [life-span] => SimpleXMLElement Object 
          (
           [begin] => 1941-05-24 
          ) 
        } 
       }  
    } 
}  

回答

1

這是一個命名空間的東西。註冊兩個名稱空間,並在運行XPath查詢時使用它們,或者滾動查看屬性。

下面是一些代碼,你的XML測試,希望它有助於

<?php 

    try { 
     $xml = simplexml_load_file("meta.xml"); 

     $xml->registerXPathNamespace('m', 'http://musicbrainz.org/ns/mmd-2.0#'); 
     $xml->registerXPathNamespace('ext', 'http://musicbrainz.org/ns/ext#-2.0'); 

     // Find the customer 
     $result = $xml->xpath('//m:artist'); 

     while(list(, $node) = each($result)) { 
      echo $node."\r\n"; 

      echo "Default Name Space Attributes: \r\n"; 
      foreach($node->attributes() as $a => $b) { 
       echo "\t".$a.":'".$b."'"; 
      } 

      echo "Name Space Attributes: \r\n"; 
      foreach($node->attributes("ext", 1) as $a => $b) { 
       echo "\t".$a.":'".$b."'"; 
      } 
     } 
    } catch(Exception $e) { 
     echo "Exception on line ".$e->getLine()." of file ".$e->getFile()." : ".$e->getMessage()."<br/>"; 
    } 


?> 
+0

謝謝老兄,你擊中了要害。 – 2012-01-05 18:40:54