How to post data as json in codeigniter?

Member

by shyann , in category: PHP Frameworks , 5 months ago

How to post data as json in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month ago

@shyann 

To post data as JSON in CodeIgniter, you can use the following steps:

  1. In your controller, you can manually encode the data array as JSON using the json_encode() function:
1
2
3
4
5
6
7
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$json_data = json_encode($data);
echo $json_data;


  1. Alternatively, you can use the $this->output->set_content_type() method to set the content type to application/json and then use the json_encode() function to output the data:
1
2
3
4
5
6
7
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$this->output->set_content_type('application/json');
echo json_encode($data);


  1. If you are posting data to an API endpoint, you can also use the curl library in CodeIgniter to send a POST request with JSON data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/endpoint');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;


These are some ways you can post data as JSON in CodeIgniter. Choose the method that best fits your requirements and implement it in your application.