2012-03-20 57 views
0

我有一个数据结构中的可变$xml,看起来像这样:如何在PHP中引用XML对象内的XML对象?

object(SimpleXMLElement)#3 (1) { 
    ["release"]=> 
    object(SimpleXMLElement)#4 (11) { 
    ["@attributes"]=> 
    array(1) { 
     ["id"]=> 
     string(36) "49d996b2-ab53-41bd-8789-3d87938dc07d" 
    } 
    ["title"]=> 
    string(9) "Pinkerton" 
    ["status"]=> 
    string(8) "Official" 
    ["packaging"]=> 
    string(10) "Jewel Case" 
    ["quality"]=> 
    string(6) "normal" 
    ["text-representation"]=> 
    object(SimpleXMLElement)#5 (2) { 
     ["language"]=> 
     string(3) "eng" 
     ["script"]=> 
     string(4) "Latn" 
    } 
    ["artist-credit"]=> 
    object(SimpleXMLElement)#6 (1) { 
     ["name-credit"]=> 
     object(SimpleXMLElement)#7 (1) { 
     ["artist"]=> 
     object(SimpleXMLElement)#8 (3) { 
      ["@attributes"]=> 
      array(1) { 
      ["id"]=> 
      string(36) "6fe07aa5-fec0-4eca-a456-f29bff451b04" 
      } 
      ["name"]=> 
      string(6) "Weezer" 
      ["sort-name"]=> 
      string(6) "Weezer" 
     } 
     } 
    } 
    ["date"]=> 
    string(10) "1996-09-24" 
    ["country"]=> 
    string(2) "US" 
    ["barcode"]=> 
    string(12) "720642500729" 
    ["asin"]=> 
    string(10) "B000000OVP" 
    } 
} 

我将如何引用名“Weezer乐队”在这里吗?或排序名称?

这里是我的尝试:用连字符

$a = (array)$xml->release['artist-credit']; // nothing 
$a = $xml->release['artist-credit']; // nothing 
$a = (array)$xml->release->artist-credit; // nothing 
var_dump($a); 

回答

1

属性需要在大括号中被引用所以是这样的:

$a = $xml->release{'artist-credit'} 

将返回的XML的艺术家信贷部分。因此,要获得名称:

$name = (string)$xml->release->{'artist-credit'}->{'name-credit'}->artist->name; 

注意,它需要被转换为字符串,否则你仍然有一个SimpleXMLElement对象。

+0

太好了,谢谢。 '$ a = $ xml-> release {'artist-credit'}'应该是'$ a = $ xml-> release - > {'artist-credit'}' – standardnerds 2012-03-20 21:15:38

+0

另外,你知道它在引用中的位置'带连字符的属性需要用大括号'引用? – standardnerds 2012-03-20 21:16:11