Search code examples
arraysjsonslim

Malformed JSON in slim framework


I have this in a route:

echo '{"result":{"code":"200","status":"success","data":'.$response->withJson($rows,200,0).'}}';

that returns this JSON:

{"result":{"code":"200","status":"success","data":HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8 [{"id":23,"ragionesociale":"consumatore","indirizzo":"000","comune":"000","provincia":71,"cap":"000","idprovincia_camera":71,"telefono":"000","fax":"000","sitoweb":"0","email":"[email protected]","codice_promo":"xxxxx","password":"xxxxx","data_adesione":"2014-09-26 07:52:23","attivato":1,"costo":0,"tipologia":1,"iva":22,"alias":"prova-it4italy-srl","pagamento":1,"merchantorderid":null,"mybankid":null,"pending":0,"paymentid":null,"logo":"","nome":null,"cognome":null,"sesso":1,"datanascita":null,"eta":null,"nazione":null,"tipologia_utente":1,"fb_token":null,"fb_id":null,"gp_token":null,"gp_id":null,"profile_img":null,"citta":null,"param":null}]}}

the problem is that I receive a second response header inside the data, that breaks the JSON. I would like to have a response of this kind:

{"result":{"code":"200","status":"success","data":[{"id":23,"ragionesociale":"consumatore","indirizzo":"000",....

Is there a way in slim to do not print the HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 part in the JSON?


Solution

  • In $response->withJson() the Content-Type of the Response is automatically set to application/json;charset=utf-8, along with the default 200 HTTP status code. So you don't have to add that manually.

    See response->withJson()

    So just doing the following should be sufficient.

    $result = new stdClass(); 
    $result->result = new stdClass(); 
    $result->result->code = "200";
    $result->result->status= "success";
    $result->result->data = $rows;
    
    echo $response->withJson($result);