2014-10-09 101 views
0

我剛開始使用簡單的XML訪問的SimpleXML屬性

解析存儲爲$ scorexml

SimpleXMLElement Object 
(
[@attributes] => Array 
    (
     [query-date-time] => 20141009T175358-0400 
     [query-string] => hidden 
     [hostname] => hidden.com 
     [result-count] => 1 
     [error-count] => 0 
     [total-count] => 9 
     [elapsed-time] => 13.0ms 
    ) 

[sports-content] => SimpleXMLElement Object 
    (
     [sports-metadata] => SimpleXMLElement Object 
      (
       [@attributes] => Array 
        (
         [doc-id] => xt.21794675-Golf_Leaderboard_XML 
         [date-time] => 20140914T150400-0400 
         [language] => en-US 
         [document-class] => event-summary 
         [fixture-key] => leaderboard 
         [revision-id] => xt.21792812-Golf_Leaderboard_XML 
        ) 

       [sports-title] => $8,000,000 The Tour Championship Leaderboard 
       [sports-content-codes] => SimpleXMLElement Object 
        (
         [sports-content-code] => Array 
          (
           [0] => SimpleXMLElement Object 
            (
             [@attributes] => Array 
              (
               [code-type] => publisher 
               [code-key] => sportsnetwork.com 
              ) 

            ) 

           [1] => SimpleXMLElement Object 
            (
             [@attributes] => Array 
              (
               [code-type] => priority 
               [code-key] => normal 
              ) 

            ) 

           [2] => SimpleXMLElement Object 
            (
             [@attributes] => Array 
              (
               [code-type] => sport 
               [code-key] => 15027000 
              ) 

            ) 

           [3] => SimpleXMLElement Object 
            (
             [@attributes] => Array 
              (
               [code-type] => league 
               [code-key] => l.pga.com 
              ) 

            ) 

          ) 

        ) 

      ) 

    ) 

) 

這些數據,並試圖讓

echo $scorexml->sports-content->sports-metadata['doc-id']; 

但得到一個錯誤,當我嘗試以迴應它:

Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';'

任何幫助表示讚賞。

+0

你能後的XML也是如此。 – slapyo 2014-10-09 22:12:51

+0

請實際閱讀[PHP手冊]中的[「Basic SimpleXML用法」一節](http://php.net/manual/en/simplexml.examples-basic.php)。大部分SimpleXML問題已經得到解答,請在提問前使用搜索。 – hakre 2014-10-10 13:45:00

回答

1

因爲元素是連字符的,所以你需要用{''}來包裝它們。屬性很好,因爲它們像數組一樣被訪問,就像['doc-id']一樣。如果它們包含連字符,則需要包裝這些元素。

$scorexml->{'sports-content'}->{'sports-metadata'}['doc-id'] 

退房例子#3: http://php.net/manual/en/simplexml.examples-basic.php

+0

非常感謝你! – 2014-10-09 22:42:36