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.
拥有PHP的XML / JSON / HTML API。 今天,我为您提供新PHP文章。 我将告诉您有关为项目开发自己的API服务的信息。 举个例子–假设我们有一个视频站点,我们将为其编写API接口。 我们教我们的API处理POST / GET请求,并以以下任何一种格式返回结果:XML / JSON / HTML。 另外,作为附加的子样本,还将向您展示如何向我们的服务发送CURL请求(例如,添加记录)。
现场演示
[sociallocker]
[社交储物柜]
打包下载
[/sociallocker]
[/ sociallocker]
Now – download the source files and lets start coding !
现在–下载源文件并开始编码!
步骤1. SQL (Step 1. SQL)
Lets add new table for 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);
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.
这只是来自youtube的随机记录。
步骤2. PHP (Step 2. PHP)
Now, lets review our test page:
现在,让我们回顾一下测试页面:
index.php (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="https://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>
<?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="https://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 beginning – our sub-sample of sending CURL request. Next file – our service file (service index file)
如您所见–大多数代码只是HTML代码。 但是在开始时–我们的发送CURL请求的子样本。 下一个文件-我们的服务文件(服务索引文件)
service.php (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;
}
<?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.
很简单的文件。 它使用“ CServices”类(主服务类)处理所有请求。 现在,我们将开发此类,该类将提供所需的所有实用程序功能。
classes / CServices.php (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;
}
}
}
<?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.
在该课程中,我添加了所有服务功能。 其中一项功能–“ getLastVideos”用于检索视频列表。 第二个'addVideo'–用于添加新视频。 当然-我没有真正添加视频-只是对过程建模。 作为函数的结果–我以请求的格式生成结果。
类/CMySQL.php (classes/CMySQL.php)
This is our regular service class to work with the database. Available in package.
这是我们与数据库一起使用的常规服务类。 封装形式。
现场演示
结论 (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!
很酷的东西,不是吗? 只需少量代码和一些巧妙的逻辑,您便可以向项目中添加功能齐全的API。 如果您有任何想分享的好主意,请确保也将其删除。 祝好运!
翻译自: https://www.script-tutorials.com/own-xmljsonhtml-api-with-php/
本文介绍如何使用PHP创建自己的XML/JSON/HTML API服务。通过实例演示,为视频网站开发API接口,处理POST/GET请求并以多种格式返回结果。同时,展示如何发送CURL请求进行记录添加。
248

被折叠的 条评论
为什么被折叠?



