我有一个使用simplexml_load_file的XML feed的php参数。 这是我的一些参数的var_dump,所以你会看到结构。
object(SimpleXMLElement)#1 (2) { ["@attributes"]=> array(1) { ["version"]=> string(3) "2.0" } ["channel"]=> object(SimpleXMLElement)#2 (5) { ["title"]=> string(20) "BWM: CarolinaCooking" ["link"]=> string(69) "http://mybluewavemedia.com/portal/v2/feeds/ovg/45_CarolinaCooking.xml" ["description"]=> string(43) "Blue Wave Media Video MRSS Feed for OVGuide" ["lastBuildDate"]=> string(31) "Mon, 04 Nov 2013 09:10:44 +0000" ["item"]=> array(29) { [0]=> object(SimpleXMLElement)#3 (4) { ["title"]=> string(32) "Vanilla Cream with Fresh Berries" ["description"]=> string(135) "Host Thom Zelenka and Chef Catherine Rabb of Fenwick's on Providence restaurant teach you how to make Vanilla Cream with Fresh Berries." ["guid"]=> string(22) "BWM-CLIENT45-ITEM34340" ["pubDate"]=> string(31) "Thu, 07 Feb 2013 05:43:12 +0000" } [1]=> object(SimpleXMLElement)#4 (4) { ["title"]=> string(33) "Meatloaf Stuffed with Blue Cheese" ["description"]=> string(153) "Host Thom Zelenka and Chef Catherine Rabb of Frenwick's on Providence restaruant teach you how to make Meatloaf Stuffed with Blue Cheese, Tomato & Bacon." ["guid"]=> string(22) "BWM-CLIENT45-ITEM34338" ["pubDate"]=> string(31) "Thu, 07 Feb 2013 05:43:12 +0000" } [2]=> object(SimpleXMLElement)#5 (4) { ["title"]=> string(23) "Creole Barbecued Shrimp" ["description"]=> string(127) "Host Thom Zelenka and Chef Catherine Rabb of Fenwick's on Provoidence restaurant teach you how to make Creole Barbecued shrimp." ["guid"]=> string(22) "BWM-CLIENT45-ITEM34336" ["pubDate"]=> string(31) "Thu, 07 Feb 2013 05:43:12 +0000" } [3]=> object(SimpleXMLElement)#6 (4) { ["title"]=> string(23) "Caribbean Banana Foster" ["description"]=> string(156) "Host Thom Zelenka and Chef Mathew Beard of the Speedway Club restaurant teach you how to make a Caribbean Bananas Foster with Toasted Coconut-Rum Ice Cream." ["guid"]=> string(22) "BWM-CLIENT45-ITEM34334" ["pubDate"]=> string(31) "Thu, 07 Feb 2013 05:43:12 +0000" } [4]=> object(SimpleXMLElement)#7 (4) { ["title"]=> string(19) "Seared Veal Cutlets" ["description"]=> string(155) "Host Thom Zelenka and Chef Mathew Beard of the Speedway Culb restaurant teach you how to make Seared Veal Cutlets with Pan Roasted Lobster and Potato Hash." ["guid"]=> string(22) "BWM-CLIENT45-ITEM34332" ["pubDate"]=> string(31) "Thu, 07 Feb 2013 05:43:12 +0000" }
如您所见,有一个名为“item”的数组。 我简单地尝试做的是创建一个foreach循环,它回显“item”数组中每个对象的标题。 我这样做了如下:
foreach($videos->channel->item as $video);
{
var_dump($video);
echo "<BR><BR>";
echo "TITLE: " . $video->title . "<BR>";
}
这根本行不通。它只打印数组中的最后一个标题。
奇怪的是,当我以这种方式创建循环时,它确实有效:
$i=0;
while($i<30) {
echo $i . $videos->channel->item[$i]->title . "<BR>";
$i++;
}
有人可以试着解释一下为什么它不能通过foreach循环工作吗?
答案 0 :(得分:-2)
这应该有效
$i=0;
foreach($videos->channel->item as $video) {
echo "TITLE: " . $video[$i]->title;
$i++;
}
编辑(其他方式):
foreach($videos->channel->item as $video) {
foreach($video as $val)
{
echo "TITLE: " . $val->title;
}
}