Over a million developers have joined DZone.

Create Your Own XML/JSON/HTML API with PHP

Develop your own API service for your PHP projects.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Today 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:

  `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`)

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:



// 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);

    header('Content-Type: text/xml');
    echo $vRes;

<!DOCTYPE html>
<html lang="en" >
        <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" />
            <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>
        <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>
                    <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>
                    <label>Method: </label>
                    <select name="type">
                        <option value="xml">XML</option>
                        <option value="json">JSON</option>
                        <option value="html">HTML</option>
                    <input type="submit" />
                <a href="index.php?action=curl">Add video (CURL)</a>

            <iframe name="results" style="width:600px;height:400px">

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).



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

// set possible limit
if (isset($_GET['limit']) && (int)$_GET['limit']) {

// process actions
switch ($_REQUEST['action']) {
    case 'last_videos':
    case 'top_videos':
    case 'add_video':

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.



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'));
            case 'xml': // gen XML result
                $sCode = '';
                if (count($aData)) {
                    foreach ($aData as $i => $aRecords) {
                        $sCode .= <<<EOF

                header('Content-Type: text/xml; charset=utf-8');
                echo <<<EOF
<?xml version="1.0" encoding="utf-8"?>
            case 'html': // gen HTML result
                $sCode = '';
                if (count($aData)) {
                    foreach ($aData as $i => $aRecords) {
                        $sCode .= <<<EOF
    <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>
                } else {
                    $sCode = '<div>Nothing found</div>';

                header('Content-Type: text/html; charset=utf-8');
                echo $sCode;

    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);
            case 'xml':
                header('Content-Type: text/xml; charset=utf-8');
                echo <<<EOF
<?xml version="1.0" encoding="utf-8"?>
            case 'html':
                header('Content-Type: text/html; charset=utf-8');
                echo '<div>' . $aData['res'] . '</div>';

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.




This is our regular service class to work with the database. Available in package.

Live Demo


download in archive



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/


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}