2012-03-20 54 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