Sending json data to a remote server – howto

21. April 2016 at 14:00


If you’re sending json requests there are different possible solutions on programming with php. Here some different explained:

1. Using Streams

‚method‘ => ‚POST‘,
‚content‘ => json_encode( $data ),
‚header’=> „Content-Type: application/json\r\n“ .
„Accept: application/json\r\n“

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);

2. Raw HTTP Post

Using Zend Framework’s HTTP client:

$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, ‚application/json‘)->request(‚POST‘);

3. Using Curl

$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK
$result     = curl_exec($curl);
$response   = json_decode($result);

4. Using Ajax

var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        var jsonObj = jQuery.parseJSON(data);
    failure: function(errorMsg) {

Please share this article von facebook & google plus or where you want, thank you!

2 Tipps für die Arbeit mit Zend Framework und Ajax – Magento

24. März 2011 at 11:40


* myAction from myController
function myAction()
if  ($this->getRequest()->isXmlHttpRequest()) {
// do the handling of your ajax request
else {
// if it's not an ajax request then do regular handling here

JSON action helper

* myAction from myController
function myAction()
if ($this->getRequest()->isXmlHttpRequest()) {
// do the handling of your ajax request
$myArrayofData = array('a','b','c');
//encode your data into JSON and send the response
//nothing else will get executed after the line above
else {
// if it's not an ajax request then do regular handling here
Weitere Tipps / nützliche Funktionen? Postet diese als Kommentar zum Artikel und ich nehme diese, wenn sinnvoll, mit in den Artikel auf.