2014-06-27 155 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

相关问题