2010-04-01 57 views
0

帮助我有一个显示一些XML IM发生的后续代码var_dump下面的输出(通过链接):需要用foreach和XML

http://bit.ly/aoA3qY

在页面的最下方,你会看到一些输出,生成此代码:

foreach ($xml->feed as $entry) { 
      $title = $entry->title; 
      $title2 = $entry->entry->title; 
     } 
echo $title; 
echo $title2; 

由于某种原因$ title2只输出一次,哪里有多个条目?

我使用$xml = simplexml_load_string($data);来创建xml。

回答

0

您在foreach循环的每次迭代中为$ title和$ tile2重新赋值。循环结束后,只有最后分配的值可以访问。
可能的替代方案:

// print/use the values within the loop-body 
foreach ($xml->feed as $entry) { 
    $title = $entry->title; 
    $title2 = $entry->entry->title; 
    echo $title, ' ', $title2, "\n"; 
} 

// append the values in each iteration to a string 
$title = $title2 = ''; 
foreach ($xml->feed as $entry) { 
    $title .= $entry->title . ' '; 
    $title2 .= $entry->entry->title . ' '; 
} 
echo $title, ' ', $title2, "\n"; 

// append the values in each iteration to an array 
$title = $title2 = array(); 
foreach ($xml->feed as $entry) { 
    $title[] = $entry->title; 
    $title2[] = $entry->entry->title; 
} 
var_dump($title, $title2);