Own XML/JSON/HTML API with PHP

Tutorials

Own XML/JSON/HTML API with PHP. Today I have new PHP article for you. I will tell you about developing 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

[sociallocker]

download in package

[/sociallocker]


Now – download the source files and lets start coding !


Step 1. SQL

Lets add new table for database to keep records about test videos:

01 CREATE TABLE IF NOT EXISTS `s189_videos` (
02   `id` int(10) unsigned NOT NULL auto_increment,
03   `title` varchar(255) default '',
04   `author` varchar(255) default '',
05   `thumb` varchar(255) default '',
06   `views` int(10) NOT NULL,
07   PRIMARY KEY  (`id`)
08 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
09 INSERT INTO `s189_videos` (`title`, `author`, `thumb`, `views`) VALUES
10 ('SURPRISE? - Ray William Johnson Video''RayWilliamJohnson''http://i1.ytimg.com/vi/4EwSAzHj8VM/default.jpg', 10000),
11 ('Sophia Grace and Rosie Hit ...''TheEllenShow''http://i4.ytimg.com/vi/KUWpd91UBrA/default.jpg', 20000),
12 ('The Thanksgiving Massacre!''FPSRussia''http://i2.ytimg.com/vi/Mgd0Hsgl8gU/default.jpg', 30000),
13 ('WE''RE MARRIED!!!!!!''CTFxC''http://i2.ytimg.com/vi/q1tsmlKXqK8/default.jpg', 40000),
14 ('Guinea Pig Boat IN OUR MAIL?!''IanH''http://i4.ytimg.com/vi/3t1YysIt598/default.jpg', 50000),
15 ('SCARED PUPPY!!!''Tobuscus''http://i1.ytimg.com/vi/8RcYkGr_IIw/default.jpg', 60000),
16 ('Review: Jawbone Up''SoldierKnowsBest''http://i4.ytimg.com/vi/WraMbywRR9M/default.jpg', 70000);

This is just random records from youtube.

Step 2. PHP

Now, lets review our test page:

index.php

01 <?php
02 // Test - using POST for add video record
03 if (isset($_GET['action']) && $_GET['action'] == 'curl') {
04     $sUrl "http://your_host_url/service.php";
05     $sData 'title=TestVideo&action=add_video&type=xml';
06     $ch = curl_init();
07     curl_setopt($ch, CURLOPT_URL, $sUrl);
08     curl_setopt($ch, CURLOPT_POSTFIELDS, $sData);
09     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
10     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
11     $vRes = curl_exec($ch);
12     curl_close($ch);
13     header('Content-Type: text/xml');
14     echo $vRes;
15     exit;
16 }
17 ?>
18 <!DOCTYPE html>
19 <html lang="en" >
20     <head>
21         <meta charset="utf-8" />
22         <title>Own XML/JSON/HTML API with PHP | Script Tutorials</title>
23         <link href="css/main.css" rel="stylesheet" type="text/css" />
24     </head>
25     <body>
26         <header>
27             <h2>Own XML/JSON/HTML API with PHP</h2>
28             <a href="https://www.script-tutorials.com/own-xmljsonhtml-api-with-php/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
29         </header>
30         <div class="container">
31             <div class="contr">
32                 <form action="service.php" target="results">
33                     <label>Action: </label>
34                     <select name="action">
35                         <option value="last_videos">Last videos</option>
36                         <option value="top_videos">Top videos</option>
37                     </select>
38                     <label>Limit: </label>
39                     <select name="limit">
40                         <option value="1">1</option>
41                         <option value="2">2</option>
42                         <option value="3">3</option>
43                         <option value="4" selected>4</option>
44                         <option value="5">5</option>
45                         <option value="6">6</option>
46                         <option value="7">7</option>
47                     </select>
48                     <label>Method: </label>
49                     <select name="type">
50                         <option value="xml">XML</option>
51                         <option value="json">JSON</option>
52                         <option value="html">HTML</option>
53                     </select>
54                     <input type="submit" />
55                 </form>
56                 <a href="index.php?action=curl">Add video (CURL)</a>
57             </div>
58             <div>Results:</div>
59             <iframe name="results" style="width:600px;height:400px">
60             </iframe>
61         </div>
62     </body>
63 </html>

As you can see – most of code is just HTML code. But in beginning – our sub-sample of sending CURL request. Next file – our service file (service index file)

service.php

01 <?php
02 require_once('classes/CMySQL.php'); // including service class to work with database
03 require_once('classes/CServices.php'); // including service class to work with database
04 $oServices new CServices();
05 // set method
06 $oServices->setMethod($_REQUEST['type']);
07 // set possible limit
08 if (isset($_GET['limit']) && (int)$_GET['limit']) {
09     $oServices->setLimit((int)$_GET['limit']);
10 }
11 // process actions
12 switch ($_REQUEST['action']) {
13     case 'last_videos':
14         $oServices->getLastVideos();
15         break;
16     case 'top_videos':
17         $oServices->setOrder('top');
18         $oServices->getLastVideos();
19         break;
20     case 'add_video':
21         $oServices->addVideo($_POST['title']);
22         break;
23 }

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

001 <?php
002 class CServices {
003     private $sMethod;
004     private $iLimit;
005     private $sOrder;
006     // constructor
007     public function CServices() {
008         $this->sMethod = 'xml';
009         $this->iLimit = 5;
010         $this->sOrder = 'last';
011     }
012     // set method
013     public function setMethod($s) {
014         $this->sMethod = $s;
015     }
016     // set limit
017     public function setLimit($i) {
018         $this->iLimit = ($i > 0 && $i < 10) ? $i $this->iLimit;
019     }
020     // set order
021     public function setOrder($s) {
022         $this->sOrder = $s;
023     }
024     // return list of videos
025     public function getLastVideos() {
026         // define order field
027         $sOrderField = ($this->sOrder == 'last') ? 'title' 'views';
028         // obtain data from database
029         $aData $GLOBALS['MySQL']->getAll("SELECT * FROM `s189_videos` ORDER BY `{$sOrderField}` DESC LIMIT {$this->iLimit}");
030         // output in necessary format
031         switch ($this->sMethod) {
032             case 'json'// gen JSON result
033                 // you can uncomment it for Live version
034                 // header('Content-Type: text/xml; charset=utf-8');
035                 if (count($aData)) {
036                     echo json_encode(array('data' => $aData));
037                 else {
038                     echo json_encode(array('data' => 'Nothing found'));
039                 }
040                 break;
041             case 'xml'// gen XML result
042                 $sCode '';
043                 if (count($aData)) {
044                     foreach ($aData as $i => $aRecords) {
045                         $sCode .= <<<EOF
046 <unit>
047     <id>{$aRecords['id']}</id>
048     <title>{$aRecords['title']}</title>
049     <author>{$aRecords['author']}</author>
050     <image>{$aRecords['thumb']}</image>
051     <views>{$aRecords['views']}</views>
052 </unit>
053 EOF;
054                     }
055                 }
056                 header('Content-Type: text/xml; charset=utf-8');
057                 echo <<<EOF
058 <?xml version="1.0" encoding="utf-8"?>
059 <videos>
060 {$sCode}
061 </videos>
062 EOF;
063                 break;
064             case 'html'// gen HTML result
065                 $sCode '';
066                 if (count($aData)) {
067                     foreach ($aData as $i => $aRecords) {
068                         $sCode .= <<<EOF
069 <div>
070     <img src="{$aRecords['thumb']}" style="float:left;margin-right:10px;" />
071     <p>Title: {$aRecords['title']}</p>
072     <p>Author: {$aRecords['author']}</p>
073     <p>Views: {$aRecords['views']}</p>
074 </div>
075 EOF;
076                     }
077                 else {
078                     $sCode '<div>Nothing found</div>';
079                 }
080                 header('Content-Type: text/html; charset=utf-8');
081                 echo $sCode;
082                 break;
083         }
084     }
085     public function addVideo($sTitle) {
086         // just simulation
087         $aData array('res' => 'Video "' $sTitle '" added successfully');
088         switch ($this->sMethod) {
089             case 'json':
090                 header('Content-Type: text/xml; charset=utf-8');
091                 echo json_encode($aData);
092                 break;
093             case 'xml':
094                 header('Content-Type: text/xml; charset=utf-8');
095                 echo <<<EOF
096 <?xml version="1.0" encoding="utf-8"?>
097 <res>
098 {$aData['res']}
099 </res>
100 EOF;
101                 break;
102             case 'html':
103                 header('Content-Type: text/html; charset=utf-8');
104                 echo '<div>' $aData['res'] . '</div>';
105                 break;
106         }
107     }
108 }

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

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!

Rate article