2023-06-03 9202

首頁(yè) » 文檔 » 開(kāi)發(fā)指南

網(wǎng)站數(shù)據(jù)轉(zhuǎn)換為JSON格式輸出

在開(kāi)發(fā)APP、小程序等應(yīng)用過(guò)程中,經(jīng)常需要以API接口形式請(qǐng)求網(wǎng)站數(shù)據(jù),以下為JSON數(shù)據(jù)輸出的一個(gè)開(kāi)發(fā)示例。

建立api/json/demo.php,代碼如下:

<?php
require '../../common.inc.php';
$lists = array();
$result = $db->query("SELECT itemid,title FROM {$DT_PRE}webpage ORDER BY listorder");
while($r = $db->fetch_array($result)) {
	$lists[] = $r;
}
echo json_encode($lists);
?>

基本流程是先引入系統(tǒng)框架,然后將數(shù)據(jù)庫(kù)里的數(shù)據(jù)查詢出來(lái),保存到數(shù)組,通過(guò)json_encode函數(shù)將數(shù)組轉(zhuǎn)換為JSON格式數(shù)據(jù)輸出。

實(shí)際開(kāi)發(fā)過(guò)程可以根據(jù)實(shí)際需要,傳遞不同的參數(shù),改變SQL語(yǔ)句來(lái)實(shí)現(xiàn)不同數(shù)據(jù)的輸出。

通過(guò)瀏覽器訪問(wèn) 網(wǎng)站地址/api/json/demo.php 調(diào)試無(wú)誤之后,在應(yīng)用中請(qǐng)求此地址即可獲取相應(yīng)的數(shù)據(jù)。

自V8.0版本,api/json/demo.php已經(jīng)默認(rèn)創(chuàng)建,可以參考此文件創(chuàng)建更多不同的文件對(duì)應(yīng)不同的功能需求。

為了訪問(wèn)入口的統(tǒng)一,V8.0同時(shí)提供了api/json.php文件,可以通過(guò)傳遞文件名參數(shù) api/json.php?file=demo 來(lái)訪問(wèn) api/json/demo.inc.php

api/json.php代碼如下:

<?php
require '../common.inc.php';
require DT_ROOT.'/include/post.func.php';
(isset($file) && check_name($file)) or $file = 'demo';
@include DT_ROOT.'/api/json/'.$file.'.inc.php';
?>

api/json/demo.inc.php代碼如下:

<?php
defined('IN_DESTOON') or exit('Access Denied');
$lists = array();
$result = $db->query("SELECT itemid,title FROM {$DT_PRE}webpage ORDER BY listorder");
while($r = $db->fetch_array($result)) {
	$lists[] = $r;
}
echo json_encode($lists);
?>

例如需要調(diào)用新聞數(shù)據(jù),可以使用如下兩種方法實(shí)現(xiàn):

一、創(chuàng)建 api/json/news.php ,參考 api/json/demo.php 編寫(xiě)邏輯,通過(guò) 網(wǎng)站地址/api/json/news.php 訪問(wèn)

二、創(chuàng)建 api/json/news.inc.php ,參考 api/json/demo.inc.php 編寫(xiě)邏輯,通過(guò) 網(wǎng)站地址/api/json.php?file=news 訪問(wèn)

建議使用第二種方式進(jìn)行開(kāi)發(fā),如果需要對(duì)訪問(wèn)進(jìn)行認(rèn)證,數(shù)據(jù)進(jìn)行加密等可以直接在api/json.php中統(tǒng)一處理。

數(shù)據(jù) JSON API 接口 APP 小程序
以上內(nèi)容是否對(duì)您有幫助?點(diǎn)擊反饋加群交流

 
公司簡(jiǎn)介   |   聯(lián)系方式   |   合作代理   |   隱私政策   |   使用協(xié)議   |   意見(jiàn)反饋