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


/ Published in: PHP
Save to your folder(s)



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

URL: http://davidwalsh.name/web-service-php-mysql-xml-json

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.