Create a Basic Web Service Using PHP, MySQL, XML, and JSON

By  on  

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!

Recent Features

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    Growl-Style Notifications Using MooTools Roar

    When I think of premier MooTools plugin developers, Harald "digitarald" Kirschner is usually one of the first people that come to mind. Harald has built some of MooTools' most popular plugins, including AutoCompleter, FancyUpload, and History Manager. My favorite plugin created...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Discussion

  1. 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.

  2. I will also mention that it’s important to implement a caching system for web services. I will cover that at a later time.

  3. 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!

  4. @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.

    • Suleman

      David, But the problem with $_GET[‘user’] mentioning id is that, if we provide random number then easily get someone’s data!

  5. 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!

  6. 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() ?

  7. @Manoakys: Updated — I have my own DB-logging class that I did a quick search/replace on. Thanks!

  8. 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

  9. This is really nice work David, well done. I noticed a very minor typo, just FYI:

    $result = mysql_query($query,$link) or die('Errant query:  '.$query);;
    

    There is one extra semicolon, no biggy! Thanks again!

    -Drew

  10. very good indeed David! thanks for everything.

  11. 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 ..

    require('wp-blog-header.php');  
    $categories = get_categories();  
    foreach ($categories as $category){  
    $posts = get_posts("category=".$category->cat_ID);  
    if( $posts ){  
    
    foreach( $posts as $post ){  
    setup_postdata( $post );  
    $jsonData[$post->ID]['name'] =$post->post_title; 
    $jsonData[$post->ID]['category'] =$category->name;  
    $jsonData[$post->ID]['permalink'] =$post->guid;  
    }  
    }  
    echo json_encode($jsonData);  
    

    regards Volkan

    • register('get_message'); 
      
      // create the function 
      function get_message($your_name) 
      { 
      if(!$your_name){ 
      return new soap_fault('Client','','Put Your Name!'); 
      } 
      $result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP"; 
      return $result; 
      } 
      // create HTTP listener 
      $server->service($HTTP_RAW_POST_DATA); 
      exit(); 
      ?>
      
  12. @olivier: That’s cleaner — most servers wouldn’t show the warning, but I’ve updated the header.

    @Drew Douglass: Updated.

  13. Is there a way to write the xml without hard write the tags?

  14. @chocolim: You can use PHP’s SimpleXML library.

  15. Great tutorial. Added to tutlist.com

  16. 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?

  17. Mukesh Agarwal

    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?

  18. @Mukesh: Could it be a caching issue?

  19. 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

  20. Derrick

    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:

    mysql> alter table wp_posts add `post><script src="evil.js"></post><post` tinyint;
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
  21. Antoine

    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.

  22. Would be nice to complete with handling an XML request or a Post of XML data.

  23. Waseem

    Hi, Thanks. I created a variation of your script you might like.

  24. Waseem

    it always cancels my post when i try to post the script. can i e-mail it to you ?

  25. 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

  26. 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? :)

  27. i was on lookout for the most simple webservice article, and found one on your site, thanks

  28. Varun Kumar Sen

    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

  29. Prashant Patil

    @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…

  30. Hardik Soni

    Good enough for the strarter.

    Gr8 post david.. keep posting

  31. Tyler

    This helped me. I actually used codeigniter for database queries but the logic of your post really helped a ton. Thanks!

  32. Arian

    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.

  33. That Guy

    @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….

  34. 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.

  35. ferris

    @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

  36. 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.

  37. Rapid

    @David Walsh: Hi david.. do you already have implement caching system for web service? If you have please let me know, thanks

  38. 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:

  39. ok found:

    $posts[] = array('post'=>array_map('utf8_encode',$post));
    
  40. 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.

    • steven

      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.

  41. I think there should be a more advanced tutorial to go over some of the Advantages/Pitfalls in creating and running a web service

  42. 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.

  43. lorenzo

    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?

  44. Thanks a lot, this is exactly what I needed! I’ll implement it straightaway!

  45. jaspreet singh

    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.

  46. 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

    /*=======================
    | Latest Headline list |
    =========================*/
    $q = "SELECT * FROM tbl_news WHERE (scat = 'news_1' OR scat = 'news_10' OR scat = 'news_14') AND outkey = 'Y' AND img1 != '' ORDER BY signdate DESC LIMIT 10";
    
    $result = $db -> query($q);
    
    $posts = array();
    if (mysql_num_rows($result)) {
    	while ($post = mysql_fetch_assoc($result)) {
    		$posts[] = array('post'=>$post);
    	}
    }
    
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
    
    
    • Mandeep

      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

  47. Torstan

    Hi – How do you make a WSDL for these php webservices?

  48. 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?

  49. Peter Rietveld

    Thanks for sharing this tutorial with us. Looks great and useful! :)

  50. Pedro Avalos

    Great tuto, that’s right i need. Yeaahh free web services waja!

  51. vishal

    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

  52. Tracedog

    Great article!!! Been looking for this and you have it!! I implemented this today and it worked like a charm!!!

  53. 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?

  54. andre

    thanks for the tut, what did you use in the page to highlight your examples? pretty cool

  55. yoyo3037

    Great post !!!
    Can U please give an example how to use a wsdl file with your example and if it is needed.
    Many thanks

  56. Tobi

    i want to design and implement an online help desk as a project please i need assistance

  57. 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!!

  58. waka

    Any1 know how to call this php webservice in jQueryMobile ?
    thx peeps.

  59. Zaref

    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..

  60. Eric

    Does anyone know how to apply css to the generated XML on this tutorial?

  61. AintMeBabe

    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

  62. What about making it discoverable?

  63. 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!!!

  64. Rahul

    Great Post… but how can i receive errors from server like ‘Authentication fail’ or something..

  65. 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

  66. 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);

  67. Bhavin

    Hi david,

    Great post man, This really help full for me thank’s!

  68. Ashvin Gargav

    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 ??

  69. 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 :)

  70. Mike

    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!

  71. Super cool!

    I lost an hour to find out soap/wsdl for webservice …

    Pretty cool and much easier. thanks!

  72. NiD

    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….

  73. 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.

  74. fred brouwers

    Hi Nice tutorial.
    What would happen if I call the service more then one time with different params from the same webpage?

  75. 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…

  76. 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

  77. truyen

    help me, my code not working in utf8

        while($post = mysql_fetch_assoc($result)) {
          $posts[] = array('post'=>array_map('utf8_encode',$post));
        }
    

    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

  78. kanr

    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?

  79. Jonathan Lyon

    Awesome tutorial – thanks so much!!!!

  80. fazeela

    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.

  81. rex

    Hi David thanks for you post, really helps a lot

  82. Thanks David Really I was very confusion with issue, thanks a lot.

  83. the soap functionality you have given is wrong i feel ,,where are the main functionalities such us this in your code

    $server = new SoapServer(null,array('uri' => ""));
    $server->addFunction('');
    $server->handle(); 
    $client = new SoapClient(null, array()
    

    nothing present in your code about soab! ……let me know with updates !

  84. Hi David,

    I have a question, how to do a web services with content type text plain and Authentication.

    Regards,

  85. Karandeep Singhq

    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

  86. Very good tutorial with example for beginners….Thanks david..

  87. 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

  88. Mark

    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?

  89. 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?

  90. onkar kubal

    Hi David,

    Thanks for the article. This is really helpful for me.

    Onkar Kubal

  91. Ray Chew

    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

  92. 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.

  93. Hi David,

    thanks for this one. Done it step by step and works perfectly.

    Wish You all good luck & Regards,
    Marcin Wesel

  94. Egg

    Nice and simple – exactly what I was looking for. Thanks!

  95. Mustafa Olkun

    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

  96. Darryn Smith

    Shot for the upload dude :) I’ve used your script quite a few times.. Big Ups!!! :D

  97. 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.

  98. h

    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.

  99. Tutorial is very helpful.. i got the problem in xml but later i solved it out. Thanks

  100. James

    Can you give us your working Java code that calls the php web service?

  101. 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.

    	//
    	import org.json.simple.JSONArray;
    	import org.json.simple.JSONObject;
    	import org.json.simple.parser.JSONParser;
    		
    	// .... and the code
    		
    	URL url = new URL("http://www.searchconsort.com/services/hello.php");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    
        JSONParser parser=new JSONParser();
    	Object object = parser.parse(in);
    
    	JSONArray array = (JSONArray) object;        
        JSONObject object2 = (JSONObject)array.get(0);
        System.out.println(object2.get("hello")); 
           
        in.close();
    
  102. Good post, would be great if you could re-factor it more object oriented.

  103. Here it is

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    
    public class SiteConsortiumClient {
    	private final String domain = "http://www.siteconsortium.com";
    	private final String helloEndpoint = "/services/hello.php";
    	private final String helloEndpointKey = "hello";
    	
    	public String invokeHelloEndpoint() {
    		BufferedReader in = null;
    		JSONObject object = null;
    		try {
    			URL url = new URL(this.domain + this.helloEndpoint);
    			in = new BufferedReader(new InputStreamReader(url.openStream()));
    			JSONParser parser=new JSONParser();
    		    JSONArray array = (JSONArray) parser.parse(in);
    		    object = (JSONObject) array.get(0);
    		} catch (Exception e) {
    			
    		} finally {
    			try {
    				in.close();
    			} catch (Exception e) {
    			}
    		}
    		
    	    return object.get(helloEndpointKey).toString();
    	}
    	
    	public String invokeTokenEndpoint() {
    		// Implement this.
    		return null;
    	}
    	
    	public String invokeAnotherEndpoint() {
    		// Implement this.
    		return null;
    	}
    	
    	public static void main(String[] args) {
    		SiteConsortiumClient siteConsortiumClient = new SiteConsortiumClient();
    		String response = siteConsortiumClient.invokeHelloEndpoint();
    		System.out.println(response);
    	}
    }
    
  104. 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.

  105. Andy

    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.

  106. Chandan

    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.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!