views:

22

answers:

1

I need one of my controller actions to return a list of names, on name per line, as plain text. The reason for this is so that it can be consumed by the JQuery autocomplete plugin which expects this format. Unfortunately, when the page renders, the \n characters won't render as newlines.

Controller

function UserController extends AppController {
    var $components = array('RequestHandler');

    function users_ajax() {
        $users = $this->User->find('all');
        $this->set('users', $users);

        $this->layout = false;
        Configure::write('debug', 0);
        $this->RequestHandler->respondAs('text');
    }
}

View

foreach($users as $user) {
    echo $user['User']['name'] . '\n';
}

Result

FIRST USER\nSECOND USER\nTHIRD USER\n

As far as I can tell, the view is being returned as plain text, however, the \n is being rendered out literally. How can I prevent this?

+5  A: 

It's not the Cake it's just the PHP. :)

Using single quotes, the characters between them are threated as string, while double quotes are interpret the \n to a new line. SO in your case:

foreach($users as $user) {
    echo $user['User']['name'] . "\n";
}

should do the magic :)

Nik
My forehead hurts from slapping it so hard. Thanks, I completely forgot about the difference between literal and interpreted strings and was treating them like javascript.
Soviut
If you need to render plain text input as HTML and have the line breaks appear, just wrap your variable to output in a nl2br( ... ) call. PHP builtin.
Travis Leleu