2012-01-05 13 views
0

xml文字列を処理するのに、simplexml_load_string関数を使用しています。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

名前空間のことです。 2つの名前空間を登録し、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

感謝の男だ願っています。 –

関連する問題