【问题标题】:PHP: foreach not forming an arrayPHP:foreach 不形成数组
【发布时间】:2012-09-01 02:54:37
【问题描述】:

我这样做了,它有效。

<?php
    function load_file($url) 
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $xml = simplexml_load_string(curl_exec($ch));
        return $xml;
    }

    $feedurl = 'http://www.astrology.com/horoscopes/daily-extended.rss';
    $rss = load_file($feedurl);

    $items = array();
    $count = 0;
    foreach ($rss->channel->item->description as $i => $description) 
    {
        $items[$count++] = $description;
    }
    echo $items[0];
?>

当我echo $items[1]; 时,它不会显示下一个。不知道我做错了什么。

【问题讨论】:

  • $rss->channel->item->description(关联)数组中有多少项?
  • var_dump($items) 看看它返回了什么。什么是xml格式?
  • 有12个,每个里面有一个
  • 似乎 foreach 只循环了一次。我的猜测是迭代$rss-&gt;channel-&gt;item
  • 这是一个 RSS 提要。抱歉这么久才回复。

标签: php xml arrays rss foreach


【解决方案1】:

这是您的 xml 示例:

<channel>
    <item>
        <description>blah</description>
    </item>
    <item>
        <description>blah1</description>
    </item>
    <item>
        <description>blah2</description>
    </item>
    <item>
        <description>blah3</description>
    </item>
</channel>

当您执行$rss-&gt;channel-&gt;item-&gt;description 时,您将获得第一个itemdescription

您需要先遍历items,然后获取每个描述。

例如:

$descriptions = array();
foreach($rss->channel->item as $item){
    $descriptions[] = $item->description;
    // note I don't need the $count variable... if you just use
    // [] then it auto increments the array count for you.
}

希望对您有所帮助。它未经测试,但应该可以工作。

【讨论】:

  • 有道理,现在就试试吧。
  • 你是那个男人,这行得通,它不会让我再接受 4 分钟的回答,我很感激你的时间,我会尽快接受你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多