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.
JSON
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
<?php header("Content-Type: application/json"); $db=new mysqli('localhost','root','','mostlikers'); $sql=$db->query("SELECT * FROM demos ORDER BY lastupdate DESC"); $json_data['my_demos']=array(); foreach($sql as $rec)//foreach loop { $json_array['name']=$rec['name']; $json_array['link']=$rec['notes']; array_push($json_data['my_demos'],$json_array); } $json = json_encode($json_data,JSON_PRETTY_PRINT); echo isset($_GET['callback'])? "{$_GET['callback']}($json)": $json; ?>
JSONP
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("http://mostlikers.2my4edge.com/php_json/index.php", 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 : http://demos.mostlikers.com/php_json/index.php?callback=mostlikers
Similar way you can pass the value to the server side.
Ex : http://demos.mostlikers.com/php_json/index.php?name=karthick&callback=mostlikers
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.
- A. P. J. Abdul Kalam
Related Topics
- Generate RSS Feed for website using php and json script
- Ajax add,view and delete using mysqli
- Active and inactive users concept using php and Ajax
- How to Make a Simple Search Engine using PHP and MySQLi
- PDO basic insert,view,update,delete with php function
- Send email with html template using php
- Login with facebook using codeigniter
Hey karthick, excellent tutorial you have covered over here, actually I was looking for the same...
ReplyDeleteThanks for the tutorial,
BTW are you a full time blogger, means are you making your living from home?