API Article get.php


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



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. if(isset($_GET['format']) && intval($_GET['num'])) {
  4.  
  5. //Set our variables
  6. $format = strtolower($_GET['format']);
  7. $num = intval($_GET['num']);
  8.  
  9. //Connect to the Database
  10. $con = mysql_connect('localhost', 'root', '') or die ('MySQL Error.');
  11. mysql_select_db('api', $con) or die('MySQL Error.');
  12.  
  13. //Run our query
  14. $result = mysql_query('SELECT * FROM recipes ORDER BY `recipe_id` DESC LIMIT ' . $num, $con) or die('MySQL Error.');
  15.  
  16.  
  17. //Preapre our output
  18. if($format == 'json') {
  19.  
  20. $recipes = array();
  21. while($recipe = mysql_fetch_array($result, MYSQL_ASSOC)) {
  22. $recipes[] = array('post'=>$recipe);
  23. }
  24.  
  25. $output = json_encode(array('posts' => $recipes));
  26.  
  27. } elseif($format == 'xml') {
  28.  
  29. header('Content-type: text/xml');
  30. $output = "<?xml version=\"1.0\"?>\n";
  31. $output .= "<recipes>\n";
  32.  
  33. for($i = 0 ; $i < mysql_num_rows($result) ; $i++){
  34. $row = mysql_fetch_assoc($result);
  35. $output .= "<recipe> \n";
  36. $output .= "<recipe_id>" . $row['recipe_id'] . "</recipe_id> \n";
  37. $output .= "<recipe_name>" . $row['recipe_name'] . "</recipe_name> \n";
  38. $output .= "<recipe_poster>" . $row['recipe_poster'] . "</recipe_poster> \n";
  39. $output .= "<recipe_quick_info>" . $row['recipe_quick_info'] . "</recipe_quick_info> \n";
  40. $output .= "<recipe_link>" . $row['recipe_link'] . "</recipe_link> \n";
  41. $output .= "</recipe> \n";
  42. }
  43.  
  44. $output .= "</recipes>";
  45.  
  46. } else {
  47. die('Improper response format.');
  48. }
  49.  
  50. //Output the output.
  51. echo $output;
  52.  
  53. }
  54.  
  55. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.