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

I need to output all books from all shelfs. This code bellow only outputs last shelf of books. Any help would be helpful.

My Controller:

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;
}

My View:

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

My Output:

only last shelf which is "Z".

My XML Data:

<?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>

you are overwriting $result it should be .= and defined before foreach begins

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;
}

The problem is here:

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

You are resetting the $result variable at the beginning of each loop.

Yes what @Shakti Singh said!