Convert PHP data to JSON API url - Mostlikers

18 August, 2015

Convert PHP data to JSON API url

Today I have discussed Convert PHP result array to JSON API URL. JSON is a lightweight data-interchange format. The current trend to develop the app and web app server side exchanging data between their servers  XML or JSON format. JSON is the easiest way to translate a JavaScript object into a PHP associative array.

Convert PHP data to JSON API url

Live Demo               Download


JSON can also be used for web service payloads et al, but it is really convenient for AJAX results. The JSON format is often used for serialising and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

Server Responsibilities

Servers MUST send all JSON API data in response documents with the header. So have write header accept type Content-type: application/JSON; charset=utf-8 code.

PHP Code to JSON

    header("Content-Type: application/json");    
    $db=new mysqli('localhost','root','','mostlikers'); 
    $sql=$db->query("SELECT * FROM demos ORDER BY lastupdate DESC"); 
    foreach($sql as $rec)//foreach loop  
    $json = json_encode($json_data,JSON_PRETTY_PRINT);
    echo isset($_GET['callback'])? "{$_GET['callback']}($json)": $json;


PHP code converted to JSONP. if you use JSON data in same domain it will work. Other domain it won't work. This because of Same origin policy, security concept that disallows such operations.

$.getJSON("", function(data) { });

it actually works, with IE but it gives security notification and does not work in Chrome in all browser. But JSONP Will support all applications.

Just add ?callback code with your specify JSON URL.

Ex : 

 Similar way you can pass the value to the server side.

Ex : 

 This code is very simple most of the API and web application developer using like that way only. The front side they will use javascript based platform. Server side GET and POST they will use JSONP  

Thank you for visiting. if have any queries write your comments below.

"My message, especially to young people is to have courage to think differently, courage to invent, to travel the unexplored path, courage to discover the impossible and to conquer the problems and succeed. These are great qualities that they must work towards. This is my message to the young people. "
                                         - A. P. J. Abdul Kalam

Related Topics

1 comment:

  1. Vickey Khachru30 May 2016 at 10:34

    Hey karthick, excellent tutorial you have covered over here, actually I was looking for the same...
    Thanks for the tutorial,

    BTW are you a full time blogger, means are you making your living from home?