在 codeigniter 中创建 Web 服务时无法获得 json 格式的响应

Cannot get response in json format when creating webservice in codeigniter

我正在 Codeigniter 中创建注册网络服务。我想获得 json 格式的响应,如果注册成功则数据将以 json 格式返回,如果数据已经存在则返回 json 响应.我对如何将值从控制器传递到视图并将其转换为 json 响应感到困惑。下面是我的代码:

Controller:

<?php

session_start(); //we need to start session in order to access it through CI

Class User_Signup extends CI_Controller {

public function __construct() {
parent::__construct();

// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');


// Load database
$this->load->model('signup_model');
}

public function registration($fname,$lname,$email) {
$data=array('first_name' => $fname,'last_name' => $lname,'email' => $email);
$result = $this->signup_model->registration_insert($data);
if ($result == TRUE) {
$this->load->view('signup_message',$data);
} else {
$this->load->view('signup_message',$data);
}
}
}

Signup_model (Model):

<?php

Class Signup_Model extends CI_Model {

// Insert registration data in database
public function registration_insert($data) {

// Query to check whether username already exist or not
$condition = "email =" . "'" . $data['email'] . "'";
$this->load->database();
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}
}
?>

View:

<?php

/* output in necessary format */
if ($format == 'json')
{
    //header('Content-type: application/json');

    echo str_replace('\/', '/', json_encode($posts));
} else
{
    header('Content-type: text/xml');
    echo '<posts>';
    foreach ($posts as $index => $success)
    {
        if (is_array($success))
        {
            foreach ($success as $key => $value)
            {
                echo '<', $key, '>';
                if (is_array($value))
                {
                    foreach ($value as $tag => $val)
                    {
                        echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
                    }
                }
                echo '</', $key, '>';
            }
        }
    }
    echo '</posts>';
} 

?>

http://localhost/MyProject/user_signup/registration/Amit/Kumar/amit

视图对于 returning json 是不必要的。只需 return json_encode($your_object) 直接来自控制器。

无论哪种方式,您正在寻找的方法是 json_encode()。