2014-06-27 154 views
0

我無法解析這個XML。我想訪問項目的數組。我嘗試過$ xml-> channel-> item和$ xml-> channel [「item」],但都不起作用。爲什麼這個XML解析只產生一個元素?

這裏是PHP代碼,我有:

$xml=simplexml_load_file("my file.xml"); 
$channel = $xml->channel; 
$items = $channel->item; 
var_dump($channel); 
var_dump($items); //This is only showing one item, when there are many 

下面是輸出爲var_dump($channel)

object(SimpleXMLElement)#4 (7) { 
    ["title"]=> 
    string(11) "Title" 
    ["link"]=> 
    string(30) "mylink/" 
    ["description"]=> 
    string(128) "description" 
    ["pubDate"]=> 
    string(31) "Fri, 27 Jun 2014 04:24:24 -0700" 
    ["generator"]=> 
    string(57) "http://Tumblr2WordPress/0.4(tumblr2wordpress.benapps.net)" 
    ["language"]=> 
    string(2) "en" 
    ["item"]=> 
    array(374) { 
    [0]=> 
    object(SimpleXMLElement)#69 (7) { 
     ["link"]=> 
     string(46) "link" 
     ["pubDate"]=> 
     string(31) "Thu, 26 Jun 2014 15:19:41 +0000" 
     ["category"]=> 
     array(2) { 
     [0]=> 
     object(SimpleXMLElement)#443 (0) { 
     } 
     [1]=> 
     object(SimpleXMLElement)#444 (1) { 
      ["@attributes"]=> 
      array(2) { 
      ["domain"]=> 
      string(8) "category" 
      ["nicename"]=> 
      string(7) "regular" 
      } 
     } 
     } 
     ["guid"]=> 
     string(46) "link" 
     ["comment"]=> 
     object(SimpleXMLElement)#445 (0) { 
     } 
     ["title"]=> 
     string(18) "Ran 8 miles today!" 
     ["description"]=> 
     object(SimpleXMLElement)#446 (0) { 
     } 
    } 
    [1]=> more here 

回答

0

開始。如果項目是一個項目組,記住你還在處理一個SimpleXML對象。使用foreach循環輕鬆遍歷每個項目並提取其屬性。

foreach($channel->item as $singleItem) { 
    //item properties are accessible for each 
} 

您擁有的另一個選擇是使用simpleXML的xpath函數返回匹配xpath的對象數組。如果你願意,我可以分享一個例子。

+0

謝謝你的工作 –

+0

很高興聽到它! – Zarathuztra

相關問題