mrid mrid - 2 years ago 124
JSON Question

Codeigniter prints a strange character before every output

I made an API in PHP codeigniter framework which returns JSON output. The output appeared fine but I wasn't able to parse it : it always gave a parsing error.

On parsing with online JSON parser, I realised all the API outputs have a weird special character in the beginning, irrespective of whether I return JSON or a simple string. ( see below )

this is the link to my API and I tested the output on JSLint

Can you help me figure out where is this character in the beginning coming from ?

This is my controller code :

public function getCleaner(){
$mobile_no = $this->input->get('mobile');
$pass = $this->input->get('pass');
if(!is_null($mobile_no) && !is_null($pass))
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('x-xss-protection: 1;');
$data = $this->cleaner_model->get_cleaner($mobile_no, $pass);
echo json_encode($data);
echo '{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"}';

And this is my model code :

public function get_cleaner($mobile, $pass){
$this->db->where("mobile1", $mobile);
$this->db->where("user_pass", $pass);
$data = $this->db->get()->row_array();

return $data;

Answer Source

The way you use to create JSON is not correct. Use following to get correct output (in ELSE block at your controller)

//this is WRONG
 echo '{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"}';

//this is correct
$arr = array('cleaner_id' => '-10', 'cleaner_name' => 'cleaner_not_found');
echo json_encode($arr);

Now you will receive correct data as

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download