如何在CodeIgniter中返回函数的完整输出?

时间:2011-04-08 12:01:08

标签: php xml codeigniter

我需要输出所有书架上的所有书籍。此代码仅显示最后一摞书。任何帮助都会有所帮助。

我的控制器:

function index()
{
  $data['books'] = $this->_books();
  $this->load->view('books_view', $data);
}

function _books() {
  $xml = simplexml_load_file('books.xml');
  foreach ($xml->shelfs as $shelf)
  {
    $result = '<optgroup label="'.$shelf['id'].'">';
    foreach ($shelf->books as $book)
    {
      $result .= '<option value="'.$book->title.'">'.$book->title.'</option>';
    }
    $result .= '</optgroup>';
  }
  return $result;
}

我的观点:

echo form_open('books#');
echo '<select name="books[]" multiple="multiple" onClick="this.form.submit()">';
echo $options;
echo '</select></form>';

我的输出:

只有“Z”的最后一个架子。

我的XML数据:

<?xml version="1.0" encoding="UTF-8" ?>
<library>

<shelfs id="A">
  <strip>
    <title>Book Title #1 for A</title>
    <author>Author Name #1 for A</author>
  </strip>
  <strip>
    <title>Book Title #2 for A</title>
    <author>Author Name #2 for A</author>
  </strip>
</comics>

...

<shelfs id="Z">
  <strip>
    <title>Book Title #1 for Z</title>
    <author>Author Name #1 for Z</author>
  </strip>
  <strip>
    <title>Book Title #2 for Z</title>
    <author>Author Name #2 for Z</author>
  </strip>
</comics>

</library>

2 个答案:

答案 0 :(得分:3)

您正在覆盖$result它应该是.=并在foreach开始之前定义

function _books() {
  $xml = simplexml_load_file('books.xml');
  $result='';
  foreach ($xml->shelfs as $shelf)
  {
    $result.= '<optgroup label="'.$shelf['id'].'">';
    foreach ($shelf->books as $book)
    {
      $result .= '<option value="'.$book->title.'">'.$book->title.'</option>';
    }
    $result .= '</optgroup>';
  }
  return $result;
}

答案 1 :(得分:2)

问题在于:

$result = '<optgroup label="'.$shelf['id'].'">';

您正在重置每个循环开头的$result变量。

是的,@Shakti Singh说的是什么!

相关问题