Create Your Own XML/JSON/HTML API with PHP
Develop your own API service for your PHP projects.
Join the DZone community and get the full member experience.
Join For FreeToday I have new PHP article for you. I will tell you about developing your own API service for your projects. As an example – let’s imagine that we have a video site for which we are going to write the API interface. We teach our API to work with POST / GET requests, and return the result in any of the following formats: XML / JSON / HTML. Also – as an additional sub-sample – will show you how to send CURL requests (for example to add records) to our service.
Live Demo | Download in package
Now – download the source files and let's start coding !
Step 1. SQL
Let's add new table for our database to keep records about test videos:
CREATE TABLE IF NOT EXISTS `s189_videos` (
`id` int(10) unsigned NOT NULL auto_increment,
`title` varchar(255) default '',
`author` varchar(255) default '',
`thumb` varchar(255) default '',
`views` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `s189_videos` (`title`, `author`, `thumb`, `views`) VALUES
('SURPRISE? - Ray William Johnson Video', 'RayWilliamJohnson', 'http://i1.ytimg.com/vi/4EwSAzHj8VM/default.jpg', 10000),
('Sophia Grace and Rosie Hit ...', 'TheEllenShow', 'http://i4.ytimg.com/vi/KUWpd91UBrA/default.jpg', 20000),
('The Thanksgiving Massacre!', 'FPSRussia', 'http://i2.ytimg.com/vi/Mgd0Hsgl8gU/default.jpg', 30000),
('WE''RE MARRIED!!!!!!', 'CTFxC', 'http://i2.ytimg.com/vi/q1tsmlKXqK8/default.jpg', 40000),
('Guinea Pig Boat IN OUR MAIL?!', 'IanH', 'http://i4.ytimg.com/vi/3t1YysIt598/default.jpg', 50000),
('SCARED PUPPY!!!', 'Tobuscus', 'http://i1.ytimg.com/vi/8RcYkGr_IIw/default.jpg', 60000),
('Review: Jawbone Up', 'SoldierKnowsBest', 'http://i4.ytimg.com/vi/WraMbywRR9M/default.jpg', 70000);
This is just random records from youtube.
Step 2. PHP
Now, let's review our test page:
index.php
<?php
// Test - using POST for add video record
if (isset($_GET['action']) && $_GET['action'] == 'curl') {
$sUrl = "http://your_host_url/service.php";
$sData = 'title=TestVideo&action=add_video&type=xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$vRes = curl_exec($ch);
curl_close($ch);
header('Content-Type: text/xml');
echo $vRes;
exit;
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>Own XML/JSON/HTML API with PHP | Script Tutorials</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h2>Own XML/JSON/HTML API with PHP</h2>
<a href="http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
</header>
<div class="container">
<div class="contr">
<form action="service.php" target="results">
<label>Action: </label>
<select name="action">
<option value="last_videos">Last videos</option>
<option value="top_videos">Top videos</option>
</select>
<label>Limit: </label>
<select name="limit">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<label>Method: </label>
<select name="type">
<option value="xml">XML</option>
<option value="json">JSON</option>
<option value="html">HTML</option>
</select>
<input type="submit" />
</form>
<a href="index.php?action=curl">Add video (CURL)</a>
</div>
<div>Results:</div>
<iframe name="results" style="width:600px;height:400px">
</iframe>
</div>
</body>
</html>
As you can see – most of code is just HTML code. But in the beginning – our sub-sample of sending CURL request. Next file – our service file (service index file).
service.php
<?php
require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CServices.php'); // including service class to work with database
$oServices = new CServices();
// set method
$oServices->setMethod($_REQUEST['type']);
// set possible limit
if (isset($_GET['limit']) && (int)$_GET['limit']) {
$oServices->setLimit((int)$_GET['limit']);
}
// process actions
switch ($_REQUEST['action']) {
case 'last_videos':
$oServices->getLastVideos();
break;
case 'top_videos':
$oServices->setOrder('top');
$oServices->getLastVideos();
break;
case 'add_video':
$oServices->addVideo($_POST['title']);
break;
}
Pretty easy file. It processing all requests with using ‘CServices’ class (main service class). Now we going to develop this class that will provide all the utility functions we need.
classes/CServices.php
<?php
class CServices {
private $sMethod;
private $iLimit;
private $sOrder;
// constructor
public function CServices() {
$this->sMethod = 'xml';
$this->iLimit = 5;
$this->sOrder = 'last';
}
// set method
public function setMethod($s) {
$this->sMethod = $s;
}
// set limit
public function setLimit($i) {
$this->iLimit = ($i > 0 && $i < 10) ? $i : $this->iLimit;
}
// set order
public function setOrder($s) {
$this->sOrder = $s;
}
// return list of videos
public function getLastVideos() {
// define order field
$sOrderField = ($this->sOrder == 'last') ? 'title' : 'views';
// obtain data from database
$aData = $GLOBALS['MySQL']->getAll("SELECT * FROM `s189_videos` ORDER BY `{$sOrderField}` DESC LIMIT {$this->iLimit}");
// output in necessary format
switch ($this->sMethod) {
case 'json': // gen JSON result
// you can uncomment it for Live version
// header('Content-Type: text/xml; charset=utf-8');
if (count($aData)) {
echo json_encode(array('data' => $aData));
} else {
echo json_encode(array('data' => 'Nothing found'));
}
break;
case 'xml': // gen XML result
$sCode = '';
if (count($aData)) {
foreach ($aData as $i => $aRecords) {
$sCode .= <<<EOF
<unit>
<id>{$aRecords['id']}</id>
<title>{$aRecords['title']}</title>
<author>{$aRecords['author']}</author>
<image>{$aRecords['thumb']}</image>
<views>{$aRecords['views']}</views>
</unit>
EOF;
}
}
header('Content-Type: text/xml; charset=utf-8');
echo <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<videos>
{$sCode}
</videos>
EOF;
break;
case 'html': // gen HTML result
$sCode = '';
if (count($aData)) {
foreach ($aData as $i => $aRecords) {
$sCode .= <<<EOF
<div>
<img src="{$aRecords['thumb']}" style="float:left;margin-right:10px;" />
<p>Title: {$aRecords['title']}</p>
<p>Author: {$aRecords['author']}</p>
<p>Views: {$aRecords['views']}</p>
</div>
EOF;
}
} else {
$sCode = '<div>Nothing found</div>';
}
header('Content-Type: text/html; charset=utf-8');
echo $sCode;
break;
}
}
public function addVideo($sTitle) {
// just simulation
$aData = array('res' => 'Video "' . $sTitle . '" added successfully');
switch ($this->sMethod) {
case 'json':
header('Content-Type: text/xml; charset=utf-8');
echo json_encode($aData);
break;
case 'xml':
header('Content-Type: text/xml; charset=utf-8');
echo <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<res>
{$aData['res']}
</res>
EOF;
break;
case 'html':
header('Content-Type: text/html; charset=utf-8');
echo '<div>' . $aData['res'] . '</div>';
break;
}
}
}
In this class I added all service functions. One of the functions – ‘getLastVideos’ is made to retrieve lists the video. Second one ‘addVideo’ – for adding new videos. Of course – I did not add the video actually – just model the process. As a result of the function – I generate the result in the requested format.
classes/CMySQL.php
This is our regular service class to work with the database. Available in package.
Live Demo
download in archive
Conclusion
Pretty cool stuff, isn`t it? With a little bit of code and some clever logic, you can add a fully functional API to your projects. If you have got any good ideas you would like to share, be sure to drop those in the comments as well. Good luck!
Source: http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/
Opinions expressed by DZone contributors are their own.
Comments