开发者

Need help with foreach and XML

开发者 https://www.devze.com 2022-12-25 02:50 出处:网络
I have the following output (via link) which displays the var_dump of some XML im generating: http://bit.ly/aoA3qY

I have the following output (via link) which displays the var_dump of some XML im generating:

http://bit.ly/aoA3qY

A开发者_Python百科t the very bottom of the page you will see some output, generated by this code:

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

For some reason $title2 only outputs once, where there are multiple entries?

Im using $xml = simplexml_load_string($data); to create the xml.


You re-assign a value to $title and $tile2 in each iteration of the foreach loop. After the loop is finished only the last assigned value is accessible.
Possible alternatives:

// 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消