Sunday, December 5, 2010

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

Copy this code to the clipboard
1/* require the user as the parameter */
2if(isset($_GET['user']) && intval($_GET['user'])) {
3
4 /* soak in the passed variable or set our own */
5 $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
6 $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
7 $user_id = intval($_GET['user']); //no default
8
9 /* connect to the db */
10 $link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
11 mysql_select_db('db_name',$link) or die('Cannot select the DB');
12
13 /* grab the posts from the db */
14 $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";
15 $result = mysql_query($query,$link) or die('Errant query: '.$query);
16
17 /* create one master array of the records */
18 $posts = array();
19 if(mysql_num_rows($result)) {
20 while($post = mysql_fetch_assoc($result)) {
21 $posts[] = array('post'=>$post);
22 }
23 }
24
25 /* output in necessary format */
26 if($format == 'json') {
27 header('Content-type: application/json');
28 echo json_encode(array('posts'=>$posts));
29 }
30 else {
31 header('Content-type: text/xml');
32 echo '';
33 foreach($posts as $index => $post) {
34 if(is_array($post)) {
35 foreach($post as $key => $value) {
36 echo '<',$key,'>';
37 if(is_array($value)) {
38 foreach($value as $tag => $val) {
39 echo '<',$tag,'>',htmlentities($val),',$tag,'>';
40 }
41 }
42 echo ',$key,'>';
43 }
44 }
45 }
46 echo '';
47 }
48
49 /* disconnect from the db */
50 @mysql_close($link);
51}
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:
Copy this code to the clipboard
1http://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

Copy this code to the clipboard
1<posts>
2 <post>
3 <post_title>SSLmatic SSL Certificate Giveaway Winners</post_title>
4 <guid>http://davidwalsh.name/?p=2304
5 </post>
6 <post>
7 <post_title>MooTools FileManager</post_title>
8 <guid>http://davidwalsh.name/?p=2288
9 </post>
10 <post>
11 <post_title>PHPTVDB: Using PHP to Retrieve TV Show Information</post_title>
12 <guid>http://davidwalsh.name/?p=2266
13 </post>
14 <post>
15 <post_title>David Walsh: The Lost MooTools Plugins</post_title>
16 <guid>http://davidwalsh.name/?p=2258
17 </post>
18 <post>
19 <post_title>Create Short URLs Using U.Nu</post_title>
20 <guid>http://davidwalsh.name/?p=2218
21 </post>
22 <post>
23 <post_title>Create Bit.ly Short URLs Using PHP</post_title>
24 <guid>http://davidwalsh.name/?p=2194
25 </post>
26 <post>
27 <post_title>Represent Your Repositories Using the GitHub Badge!</post_title>
28 <guid>http://davidwalsh.name/?p=2178
29 </post>
30 <post>
31 <post_title>ZebraTable</post_title>
32 <guid>http://davidwalsh.name/?page_id=2172
33 </post>
34 <post>
35 <post_title>MooTools Zebra Table Plugin</post_title>
36 <guid>http://davidwalsh.name/?p=2168
37 </post>
38 <post>
39 <post_title>SSLmatic: Quality, Cheap SSL Certificates and Giveaway!</post_title>
40 <guid>http://davidwalsh.name/?p=2158
41 </post>
42</posts>
Take this next sample URL for example:
Copy this code to the clipboard
1http://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

Copy this code to the clipboard
1{"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!

23 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you so much for giving me a great website for blog comments .. Dropmylink is really great site and i have been using from 2 days and i know this from your blog.Appreciated

    ReplyDelete
  3. Great post! A well-written resource to anyone looking to boost their SEO through blog commenting. The tools mentioned will also go a long way in making the entire process much more efficient and effective.

    ReplyDelete
  4. Its an awesome post and is quite meaningful.Commenting on blogs related to your niche helps a lot.We would always be careful about what we write in our comments. I have seen many bloggers whose comments were marked as spam just because they they contained few words and were only left for backlink purposes.

    ReplyDelete
  5. Great post!Thanks for sharing this list!It helps me a lot finding relevant blog in my niche!

    ReplyDelete
  6. This is a great list to create a lots of backlinks using commenting. Some of them are in my radar all the time and few of them were new to me. But instead of using any tool for finding new blogs, I normally use google queries to find out related blogs. Keep posting such wonderful posts.

    ReplyDelete
  7. Thanks for sharing high domain authority blog sites its difficult to find thanks once again.

    ReplyDelete
  8. This is really helpful. Thanks for sharing this list, Anil. I guess the most important thing is to steer clear away from spam moderators by putting comment that actually MATTER. Anyways, I’ll be using these blogs. Thank you so much!

    ReplyDelete
  9. Thank you Anil for sharing such a wonderful blog commenting list. DO you have a list of Career related blogs for commenting?

    ReplyDelete
  10. Amazing collection of blog commenting sites. High domain authority sites are quite difficult to find. Thank you for sharing the list. Expecting more of similar posts from your end.

    ReplyDelete
  11. I must say that this blog helped me a lot for gaining a lot of information but it could be great help if you could list other blog commenting sites for travel websites.

    ReplyDelete
  12. Thanks again for sharing a wonderful list. I was wondering u did not mention the most sought after terminology used in all the blog commenting articles and that being dofollow. So, are these a mix of dofollow and nofollow attribute blogs or one should overlook this factor while commenting?

    ReplyDelete
  13. Yeah most of the words you can’t really use in normal sentences, like ‘I have good knowledge in math’ and if you replace it with the words on this list it just doesn’t work.

    ReplyDelete
  14. This was Very useful. Thank you ��! You just have to know when and where to use these wonderful words. They all replace and come in beautifully. ��

    ReplyDelete
  15. This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. Clipping Path Service

    ReplyDelete
  16. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... cleaning service Dubai

    ReplyDelete
  17. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! mejores hospederias

    ReplyDelete
  18. I would like to say that this blog really convinced me to do it! Thanks, very good post. trafficize

    ReplyDelete
  19. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. SEO CDMX

    ReplyDelete
  20. I would like to this blog for carpet steam cleaning Melbourne. Also I like this blog about carpet cleaning. It has very useful information for carpet steam cleaning.

    ReplyDelete
  21. Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people.
    php software developers

    ReplyDelete


  22. I read this article. I think You put a great deal of exertion to make this article. I like your


    fuct

    ReplyDelete