PHP XML处理,读取属性

时间:2012-01-05 17:50:00

标签: php xml xml-parsing

我正在使用simplexml_load_string函数来处理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 个答案:

答案 0 :(得分: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/>";
    }


?>