PHP: How to Create a Simple JSON or XML Web Service CodeUnit 07 DEC 2011

Thanks to Twitter, the idea of accessible, useful, and more importantly, simple web services has really latched on in the world of web development. Bascially all a web service is, is a simple URL that when hit with or without specified parameters, returns some data in either JSON or XML (or quite frankly whatever you want it to return) format.

Here is a quick example to show you just how easy it is to develop a simple, basic web service of your own in PHP:

//database connection
$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');

//format parameters. Note default of JSON for format parameter
$format = key_exists('format', $_POST) ? strtolower($_POST['format']) : 'json';
$format = in_array($format, array('json', 'xml')) ? $format : 'json';
$code = key_exists('code', $_POST) ? strtolower($_POST['code']) : 'survey';
$input = trim($code);

//output variables
$status = 0;
$name = '';
$message = '';

//check if we can find a record in the database
$campaignrs = mysql_query("SELECT `campaign-name` FROM `campaigns` WHERE `campaign-code` = '$input' LIMIT 1");
if (mysql_num_rows($campaignrs) > 0) {
        $campaign = mysql_fetch_assoc($campaignrs);
        $status = 1;
        $message = 'Valid Code';
        $name = $campaign['campaign-name'];
} else {
        $status = 0;
        $message = 'Invalid Code';
        $name = '';

//build output array
$output = array('status' => $status, 'message' => $message, 'name' => $name);

/* output in necessary format */
if ($format == 'json') {
    header('Content-type: application/json');
    echo json_encode($output);
} else {
    header('Content-type: text/xml');
    echo '';
    echo '' . $status . '';
    echo '' . $message . '';
    echo '' . $name . '';
    echo '';

 /* disconnect from the db */

Simple. The web service provides an object with three keys, namely status, name, and message. You can control the output with the format switch, and the code parameter in this case is what we are using to initiate some sort of result or check.

That should be enough to get you up and running I reckon! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Nice post!

    • Yup, needed to hastily figure out how to do this in order to give Matthew something to work with the other day! :)

  • Watch out for SQL injection — you’re placing $input directly into your SQL query and can thus be blown out of the water…

    • Thanks for the note Sven, but not really the focus of the tutorial – its purpose is simply to indicate how one would build a simple web service, not actually give a full blown production script! :)