6
I need to return $items array from 'http://localhost:8000/cart/viewall'
controller action. But all i get is this error.

The Response content must be a string or object implementing __toString(), "array" given.

This is my code,

 /**
 * @Route("/cart/viewall")
 * @Template()
 */
public function viewallAction() {
    $items = array(1 => 'item 1', 2 => 'item 2');        
    return new Response($items);
}     

It would be great help if someone can supply a solution.

8
  • 3
    new JsonResponse($items); and you have to use the good use ....\JsonResponse; Commented Jan 3, 2016 at 9:46
  • 1
    What do you mean with "I need to return an array"? The controller in Symfony is responsible to return a response and since an HTTP response contains a body which is just a string your response must contain a string to. Do you maybe mean you want to return a JSON encoded array? Commented Jan 3, 2016 at 9:46
  • 1
    Think about the new Response like a call to echo. This is a response to the browser and it has to be a string. Commented Jan 3, 2016 at 9:51
  • 1
    Thanks I think I have to return a json array then. Commented Jan 3, 2016 at 9:51
  • 1
    How do you use the result from /cart/viewall? Ajax or what? Commented Jan 3, 2016 at 9:53

1 Answer 1

9

Use JsonResponse instead.

Example :

$items = array(1 => 'item 1', 2 => 'item 2');
return new JsonResponse($items);

see http://symfony.com/doc/current/components/http_foundation/introduction.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.