mrid
mrid

Reputation: 5796

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);
        if(!empty($data))
            echo json_encode($data);
        else 
            echo '{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"}';
    }
}

And this is my model code :

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

     return $data;
}

Upvotes: 0

Views: 1071

Answers (1)

Rejoanul Alam
Rejoanul Alam

Reputation: 5398

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

{"cleaner_id":"-10","cleaner_name":"cleaner_not_found"} 

Upvotes: 1

Related Questions