Question

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?

Was it helpful?

Solution

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top