Create a Basic Web Service Using PHP, MySQL, XML, and JSON
Web services are taking over the world. I credit Twitter's epic rise to the availability of a simple but rich API. Why not use the same model for your own sites? Here's how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.
The PHP / MySQL
/* require the user as the parameter */ if(isset($_GET['user']) && intval($_GET['user'])) { /* soak in the passed variable or set our own */ $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default $user_id = intval($_GET['user']); //no default /* connect to the db */ $link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB'); mysql_select_db('db_name',$link) or die('Cannot select the DB'); /* grab the posts from the db */ $query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts"; $result = mysql_query($query,$link) or die('Errant query: '.$query); /* create one master array of the records */ $posts = array(); if(mysql_num_rows($result)) { while($post = mysql_fetch_assoc($result)) { $posts[] = array('post'=>$post); } } /* output in necessary format */ if($format == 'json') { header('Content-type: application/json'); echo json_encode(array('posts'=>$posts)); } else { header('Content-type: text/xml'); echo '<posts>'; foreach($posts as $index => $post) { if(is_array($post)) { foreach($post as $key => $value) { echo '<',$key,'>'; if(is_array($value)) { foreach($value as $tag => $val) { echo '<',$tag,'>',htmlentities($val),'</',$tag,'>'; } } echo '</',$key,'>'; } } } echo '</posts>'; } /* disconnect from the db */ @mysql_close($link); }
With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.
Take the following sample URL for example:
http://mydomain.com/web-service.php?user=2&num=10
Now, we can take a look at the possible results of the URL.
The XML Output
<posts> <post> <post_title>SSLmatic SSL Certificate Giveaway Winners</post_title> <guid>https://davidwalsh.name/?p=2304</guid> </post> <post> <post_title>MooTools FileManager</post_title> <guid>https://davidwalsh.name/?p=2288</guid> </post> <post> <post_title>PHPTVDB: Using PHP to Retrieve TV Show Information</post_title> <guid>https://davidwalsh.name/?p=2266</guid> </post> <post> <post_title>David Walsh: The Lost MooTools Plugins</post_title> <guid>https://davidwalsh.name/?p=2258</guid> </post> <post> <post_title>Create Short URLs Using U.Nu</post_title> <guid>https://davidwalsh.name/?p=2218</guid> </post> <post> <post_title>Create Bit.ly Short URLs Using PHP</post_title> <guid>https://davidwalsh.name/?p=2194</guid> </post> <post> <post_title>Represent Your Repositories Using the GitHub Badge!</post_title> <guid>https://davidwalsh.name/?p=2178</guid> </post> <post> <post_title>ZebraTable</post_title> <guid>https://davidwalsh.name/?page_id=2172</guid> </post> <post> <post_title>MooTools Zebra Table Plugin</post_title> <guid>https://davidwalsh.name/?p=2168</guid> </post> <post> <post_title>SSLmatic: Quality, Cheap SSL Certificates and Giveaway!</post_title> <guid>https://davidwalsh.name/?p=2158</guid> </post> </posts>
Take this next sample URL for example:
http://mydomain.com/web-service.php?user=2&num=10&format=json
Now, we can take a look at the possible results of the URL.
The JSON Output
{"posts":[{"post":{"post_title":"SSLmatic SSL Certificate Giveaway Winners","guid":"http:\/\/davidwalsh.name\/?p=2304"}},{"post":{"post_title":"MooTools FileManager","guid":"http:\/\/davidwalsh.name\/?p=2288"}},{"post":{"post_title":"PHPTVDB: Using PHP to Retrieve TV Show Information","guid":"http:\/\/davidwalsh.name\/?p=2266"}},{"post":{"post_title":"David Walsh: The Lost MooTools Plugins","guid":"http:\/\/davidwalsh.name\/?p=2258"}},{"post":{"post_title":"Create Short URLs Using U.Nu","guid":"http:\/\/davidwalsh.name\/?p=2218"}},{"post":{"post_title":"Create Bit.ly Short URLs Using PHP","guid":"http:\/\/davidwalsh.name\/?p=2194"}},{"post":{"post_title":"Represent Your Repositories Using the GitHub Badge!","guid":"http:\/\/davidwalsh.name\/?p=2178"}},{"post":{"post_title":"ZebraTable","guid":"http:\/\/davidwalsh.name\/?page_id=2172"}},{"post":{"post_title":"MooTools Zebra Table Plugin","guid":"http:\/\/davidwalsh.name\/?p=2168"}},{"post":{"post_title":"SSLmatic: Quality, Cheap SSL Certificates and Giveaway!","guid":"http:\/\/davidwalsh.name\/?p=2158"}}]}
Creating a basic web service is very simple and encourages your users to spread the word about your website or service. Want more traffic? Want your website to grow without you putting in all the effort? Create a web service!
Hi David, yet another great post!
Although you may want to think about using mysql_real_escape_string on that $_GET[‘user’] string to prevent SQL Injection, it would be a shame to see all that hard work wasted otherwise.
Thanks,
Anthony.
I will also mention that it’s important to implement a caching system for web services. I will cover that at a later time.
David, this is absolutely brilliant.
I wouldn’t have known where to start with something like this — but now you have explained it I can give it a go.
Thank you!
@Anthony Sterling: In the case of the user ID, I’m using intval() to convert whatever is passed to a number. If someone tries a SQL injection using the $_GET[‘user’] var, their text simply gets changed to “0” for the username. No problems there.
That intval idea is great, especially since a val of 0 will return nothing anyway since indexes start with 1 in mysql.
David, But the problem with $_GET[‘user’] mentioning id is that, if we provide random number then easily get someone’s data!
David, this is great … thank you for posting it up. I’ve been looking for some good code to do this for a while now. I’ve seen other approaches with obvious holes, so your well thought out solution is much appreciated. Thanks again!
Hi, what function log does? From php manual http://lt.php.net/manual/en/function.log.php its logarythmic function.
Maybe you wanted to write die() ?
@Manoakys: Updated — I have my own DB-logging class that I did a quick search/replace on. Thanks!
great post. Just a thing, tiny detail: when you test for parameters in the $_GET array, you should use the isset() function, otherwise you get a index warning if the parameter is not set:
$number_of_posts = isset($_GET[‘num’])? intval($_GET[‘num’]) : 10; //10
I know, warnings are not the end of the world, but it’s better to avoid them when possible, so they don’t pollute the logs unecessarily and make you miss a real unexpected warning or error. And yeah I know warnings can be disabled, but I don’t recommand it, they can be useful
This is really nice work David, well done. I noticed a very minor typo, just FYI:
There is one extra semicolon, no biggy! Thanks again!
-Drew
very good indeed David! thanks for everything.
Hey David, i wrote a related article about doing JSON requests to a wordpress database (mootools based). The php part is a bit shorter… The mootools part can also be found here ..
regards Volkan
@olivier: That’s cleaner — most servers wouldn’t show the warning, but I’ve updated the header.
@Drew Douglass: Updated.
Is there a way to write the xml without hard write the tags?
@chocolim: You can use PHP’s SimpleXML library.
Great tutorial. Added to tutlist.com
Hi David,
Great post I’ve been wanting to do this for a couple of my sites. Have you considered a php tutorial on consuming these web services with cURL or other methods?
Hi David,
Thanks for the article. Very good explaination. I have a small doubt though : When I try to make some changes in the code, is it reflected for every output? I am using the same code to create my web service (which gives JSON output), but when I made some code changes, I did not get the new json output but the same old results. Instead, when I tested the output on a different browser, I got the expected new results. Am I doing something wrong?
@Mukesh: Could it be a caching issue?
David,
Nice article. Thought it might be good for you to take a look at one that i stumbled upon just the other day whilst researching this webservices area. this approach mimics the .net 3.5 scriptservice functionaility. i think (apart from the unobtrusive javascript anomoly) that it’s a great way to invoke asyncronys webservices:
http://www.codeproject.com/KB/net-languages/ScriptServiceInPHP.aspx
be interested to hear you thoughts on this approach.
cheers
jimi
You should also use htmlentities () to sanitize your $tag variables, just in case. MySQL considers XML special characters to be valid characters for field names, so if your database credentials were ever compromised, someone could ruin your day:
Hi David,
If you want to work in UTF-8, you should add:
mysql_query("SET NAMES 'utf8'");
after the connection…And in international context, htmlentities() should be removed because it prevent the XML to be well formed.
Would be nice to complete with handling an XML request or a Post of XML data.
Hi, Thanks. I created a variation of your script you might like.
it always cancels my post when i try to post the script. can i e-mail it to you ?
David,
Thanks for such a great tutorial… your tutorials on Mootools have saved my tail on a number of occasions… I plan on trying your solution soon!
Thanks!
Dennis
Ive been looking for an article like this, but i need a little more help…the rest of the code :) I need to create a webservice (jSON) for an iphone app that will read from and write to a server via php-xml-mySQL. I used to be an asp3 programmer so i know apps can communicate to db but im a bit lost at the moment because its been a while and jSON is new to me. Any help? Ideas? :)
i was on lookout for the most simple webservice article, and found one on your site, thanks
Hi David,
Really i m totally impressed with you.. your blog has helped me many time when i was in trouble during work on different APIs. Now again i have one issue. My question is : Is there any unofficial api for yahoomail/hotmail which doesn’t need 3rd party authentication? or Is there any web services by yahoomail/hotmail to retrieve a user inbox mail and display on my website after user login?
Regards,
Varun
@Varun Kumar Sen: I have same issue and looking for same library or PHP code.. but i think David is not interested to help us in this regard…
Good enough for the strarter.
Gr8 post david.. keep posting
This helped me. I actually used codeigniter for database queries but the logic of your post really helped a ton. Thanks!
If you’re just use this for some blog posts, why not use RSS. That is the format that is designed for it. If you use RSS people can read your posts in other readers to and do not have to create a custom script just to read some blog posts.
I understand that this is just an example how you could do it, and of course, for other data you can’t use the RSS format and must create your own.
@Arian: I think your second paragraph answered your own question. Also, this is the same way the XML for those RSS feeds are generated, soo….
Superb post for rest. I have a plan to implement this kind of solution to my site for admining remotely from my computer.
thanks for this post.
@mars: Hi Mars, I need to do almost exactly what you describe. Did you figure out the code needed? If so. can you share it with me?
Thanks
Ferris
if i want to make semantic web service, can i use PHP to make it??
because data in semantic database are based on ontology.
so if we use data in semantic we only need query.
@David Walsh: Hi david.. do you already have implement caching system for web service? If you have please let me know, thanks
Hello,
I have some error with french language:
Erreur d’analyse XML : entité non définie
The DB is UTF8…
How I can resolve issue ?
Thanks
@Rapid:
ok found:
New to JSON.
While passing the format=json parm in the URL, the browser is asking me to save the file. Is this expected? or should it display the results in the browser?
Depends on the browser. The idea behind this is that you’d grab the JSON in an automated fashion.
Depends on the browser. The idea behind this is that you’d grab the JSON in an automated fashion.>>>
Does it mean that if the call comes from an app for example it returns the call for it to be processed cross domain?
Trying to figure out how to return the data to my mobile app for display.
Basically i pass variables from a search form to this script via json an it will reply? right.
Thanks so far very usefull since i’m totally noob.
I think there should be a more advanced tutorial to go over some of the Advantages/Pitfalls in creating and running a web service
Hello, this is a great article for me
In the past i have created web services using SOAP and it was much more fiddly then this method, and in general i could of just used this method and passed in variables in the URL.
This will be sooo much easier.
This is off the subject but, how did you set this page up where people’s picture , name , and comments are posted with the ability to reply to?
Thanks a lot, this is exactly what I needed! I’ll implement it straightaway!
hi , good tut for xml.
but everytime i run json as default in wamp , lets say my file test.php .
In which i pasted ur code. JSON as default.
Each time i run(refresh) it asks me to save the file of same name test.php when i do save in that json result is displayed.
Please tell, y its happening like this.
I want to use this json result for my ANDROID APP.
Hi,
I finally find it. Thanks a lot for the code
I have some small question to ask. Can I change the extension to .json and inside with the php code? but when I do that it only show me the php code. Am I doing something wrong?
This is my code
Hi Lewis,
I am struggling with Web Services, could you please share some sample code on how to make a php service connected to a mysql database and a client page to get top 10 rows ..probably like rss ?
Many thanks in advance
Hi – How do you make a WSDL for these php webservices?
It is a great post!
Could you please explain more where and how to use it?
Does any service consumer need to register a user in your website?
Thanks for sharing this tutorial with us. Looks great and useful! :)
Great tuto, that’s right i need. Yeaahh free web services waja!
This is the web service where i can pass data from my mysql database to json formate,But if i want some data posted back by iphone then how i can do this? Is this any webservice for this
Great article!!! Been looking for this and you have it!! I implemented this today and it worked like a charm!!!
Hi David,
Awesome Post..
I am a regular follower of your blog, but I Have a doubt in this post, I used the code you have given as it is but when I executed it with format as “json” I was asked to download the same named php file in which i have written the code but the file contains the json output. Why is it happening so?
thanks for the tut, what did you use in the page to highlight your examples? pretty cool
Great post !!!
Can U please give an example how to use a wsdl file with your example and if it is needed.
Many thanks
i want to design and implement an online help desk as a project please i need assistance
Hay,
David
Its really cool KISS type explanation.
Now if i want to store this web services to mobile db then how can we store parsed XML or JSON data to JavaScript Object ?
I know its different question may not related you but if you know and can help me its my pleasure!!
Any1 know how to call this php webservice in jQueryMobile ?
thx peeps.
Hi,
Is there any link or tutorial how to create client program to access webservices?
Appreciates you can give us sample clieant program how to interact to this webservice.
Tqvm..
Does anyone know how to apply css to the generated XML on this tutorial?
Just wondering, what to do if there is gonna be a special character in a database like &. If something like that turns to be in databse you’ll have an xml error
What about making it discoverable?
Hi David,
Another great post from your side.
cool explanation!! I was searching for it for last week finally got from this post!!
Thanks a lot!!!
Great Post… but how can i receive errors from server like ‘Authentication fail’ or something..
Hi David gret info.
Here I have created web service using nusoap php lib.Want to share here for php users as open source.
web services using php
Thank you so much for this script. It is perfect for what I wanted to do.
I had a little difficulty with the xml output running into errors. I found solutions on stackoverflow. This is what worked for me:
$val = htmlentities($val);
$val = preg_replace(“/&#?[a-z0-9]{2,8};/i”,””,$val);
$val = preg_replace(“/&#?[a-z0-9]+;/i”,””,$val);
$val = html_entity_decode($val);
Hi david,
Great post man, This really help full for me thank’s!
Hi, david thanks for this nice code..
I have a question
I use this code
************************
echo “”;
print_r($posts);
************************
it gives me :
Array
(
[0] => Array
(
[post] => Array
(
[userid] => 101
[posted_on] => 2011-12-31 05:50:05
[avatar] => images/avatar/S1_123111055005Iphone_Driver.jpg
[thumb] => images/avatar/S1_123111055005Iphone_Driver.jpg
[latitude] => 22.717985
[longitude] => 75.888658
[username] => S2
[email] => Vani_sachu1@yahoo.co.in
[distance] => 0.73
[Time] => 0
[RecordNo] => 10
)
)
but i want to get that $post again how can i get it throuh any php function ??
Great post….
I used “most” of this code at BlueHost where my website is…
I used the Cgi-Bin folder for my website, and tweaked the obvious changes to the code for login, db, and sql query. The other thing I had to do was wrap the code in tags…
To my pleasure, it worked great…
Now I can start doing the real dev :)
I was look for something exactly like this to use for developing an iOS app and needed a way of outputting website data to JSON… I actually needed more simple version without pesky users, but this script is excellent and very easy to tailor to my needs.
Thank you very much Mr Walsh.. another excellent post with a very useful script!
Super cool!
I lost an hour to find out soap/wsdl for webservice …
Pretty cool and much easier. thanks!
Hi Devid,
This is nice work…but I’ve got a problem with XML creation..
I am working on localhost now….this is working fine for JSON but for XML when the data is very large say, about 50000..it produces an error that,
XML Parsing Error: not well-formed
Location: http://localhost/BNWebService/BNWebService.php?query=search&format=xml
Line Number 1, Column 5377787:
why this error and what to do now….
hi David, you are very correct, now a days many company have started using web services because of it’s fast and secure services. We provide Web Services Training in ahmedabad and help professionals of php, asp.net and java to get their hands on on web services.
Hi Nice tutorial.
What would happen if I call the service more then one time with different params from the same webpage?
Hi David,
Nice example of the web service.
I just want to know that you didn’t mentioned any security majors. I have checked on other sites and the used SOAP, REST or XML-RPC. What is the use of SOAP, REST and XML-RPC. You didn’t use any of them in your code.
Please let me know what is the use of SOAP, REST and XML-RPC when we are working with web services. Can we go without SOAP, REST and XML-RPC?
Also tell me something about security in web services..
Reply….
Thanks in advance…
he is using your code or you are using his code and neither one put any retribution to the “real” author. anyways… here is the link.
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
help me, my code not working in utf8
result of error
Ti\u00c3\u0083\u00c2\u00aau \u00c3\u0084\u00e2\u0080\u0098\u00c3\u00a1\u00c2\u00bb\u00c2\u0081 kh\u00c3\u0083\u00c2\u00b4ng d\u00c3\u00a1\u00c2\u00ba\u00c2\u00a5u
when i access direct “http://localhost/web-service.php?user=2&num=10”
show error
XML Parsing Error: junk after document element
Location: http://localhost/web-service.php?user=1&num=10
Line Number 2, Column 1:Notice: Undefined index: format in D:\xampp\htdocs\web-service.php on line 8
^
Why?
Awesome tutorial – thanks so much!!!!
Hello David
Thank you for such a nice tutorial,i am using your code as a template for creating my web service,but i have many modifications, i would like to move to a page where a username and password is required,after clicking on submit,it should display the username and password in the json format.
Hi David thanks for you post, really helps a lot
Thanks David Really I was very confusion with issue, thanks a lot.
the soap functionality you have given is wrong i feel ,,where are the main functionalities such us this in your code
nothing present in your code about soab! ……let me know with updates !
Hi David,
I have a question, how to do a web services with content type text plain and Authentication.
Regards,
Hi David thanks for your tutorial. It’s really helpful for me.
I want to know how I can create web service for maintaining sessions.
For example when login into browser and our session is maintained on server.
How it would be possible in case of iPhone + php web service.
So that I can check a user is logged in or not.
Please give me an idea.
You can reply on email also
kind regards,
Karandeep Singh
Very good tutorial with example for beginners….Thanks david..
who can write a PHP function, know what jQuery is, can handle their CSS well, but would like some insider info on how a web service is built from scratch. How should I organize my files, where should I keep my functions, how should I start planning the thing, how should I connect to the database, how should I handle AJAX calls and how should I manage my 404 pages are just some of the questions I try to shed some light on here.
Link: http://biitbook.com/books/detail/how-to-create-a-web-service-start-to-finish
I have used the code, however one of the tables contains html and this seems to be creating an issue
if you have a look at http://www.jasondoyleracing.com/webservices/news.php you will see this does not create an xml file but http://www.jasondoyleracing.com/webservices/fixtures.php does. Any ideas?
hi david, i have created a simple php file which accepts the parameter and displays the desired result… my mobile app fetches the result by sending request every second…. is it correct to send request every second to achieve a kind of web service?
Hi David,
Thanks for the article. This is really helpful for me.
Onkar Kubal
Hello David, very much thanks to you for this post. It is much more help full to me.
i were searching from a large time like what you have post. Thanks again and please also inform me some more examples like it for the Web Services
My project is much different from this tutorial but it helps me completely to under working with json and xml. First time I am little confused with xml but later i fully understand about xml.
By the way david, thanks a lot for this tutorial.
Hi David,
thanks for this one. Done it step by step and works perfectly.
Wish You all good luck & Regards,
Marcin Wesel
Nice and simple – exactly what I was looking for. Thanks!
the_content column is error.
$sql = “select * from wp_posts where post_status=’publish’ and post_type=’post’ order by ID DESC limit 0,1”;
$query = mysql_query($sql);
$posts = array();
while ($result = mysql_fetch_assoc($query)):
$this->posts[] = array(“posts” => $result[“post_content”]);
endwhile;
http://www.ippa.biz/json_error.png
Shot for the upload dude :) I’ve used your script quite a few times.. Big Ups!!! :D
Hey man great post. I have a concern with the above $_GET[‘user’] parameter. Why would you want the user to be an int? Wouldn’t it make more sense to get the username from the user attempting to read the post? And then retrieve the user_id From your USERS table where the username = $_GET[‘username’] this would eliminate being able to send random integers to receive posts you should not have the access to.
Anyways, this is how simple php/mysql makes webservice creation. Great Example. Great Tutorial.
Hey man great post. I have a concern with the above $_GET[‘user’] parameter. Why would you want the user to be an int? Wouldn’t it make more sense to get the username from the user attempting to read the post? And then retrieve the user_id From your USERS table where the username = $_GET[‘username’] this would eliminate being able to send random integers to receive posts you should not have the access to.
Anyways, this is how simple php/mysql makes webservice creation. Great Example. Great Tutorial.
Tutorial is very helpful.. i got the problem in xml but later i solved it out. Thanks
Can you give us your working Java code that calls the php web service?
James – For the links to the Java library go here http://www.siteconsortium.com/h/D0000C.php. Also there is the code to a PHP service.
Here is one way to get it done.
Good post, would be great if you could re-factor it more object oriented.
Here it is
Sorry am kinda new to webservice. tried tweaking this code to get data from a database for daily devotional …but i always get no object found error. Pls kindly help out.
Just wanted to say thank you for the article. I didn’t know where to start but this was so straightforward that I built my first API in just a few hours. Great stuff.
hi i am new in android, and for my app i want to make a web-services in php but i don’t have any idea how i make web-services in php, if anyone send me some web-services php file on my mail id then it is very helpful for me to understand how to build a web-services in php, my email id is chandan24892@gmail.com
Thank you in Advance.