I have been using file_get_contents and curl to fetch data from other web sites .But we all know what happens if the owner of that site changes its html .So many people say we might make an API inorder to avoid these things .(1)My first qeustion is can we do this with any kind of web site or is this only for big web sites such as youtube twitter facebook ??
(2) second question is how to make this ? can somebody explain this briefly or please give me the guides
I am so sorry i know this is just a stupid question to ask here ,but after searching for few days still I dont have proper idea about API
如何使用PHP制作API [关闭]
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- doucong8553 2015-08-22 22:20关注
For who? For what?
Anyone. Anywhere. Anything.
How to make it
There is many way to make an API.
First, you need to know some things:- Return values method or Content-Type (JSON, XML..)
- Allowed websites origins
To explain how to create an API,
I'll use JSON. To define Content Type use the header() function :header('Content-Type: application/json');
To define allowed websites origins (only if another website gonna use this API):
header('Access-Control-Allow-Origin: http://yourwebsite.com');
Once this is done, you can begin your API.
It's like any PHP code, here's an example:First, you'll maybe need to get all $_GET variables.
As for me, I save them all like this:if(!empty($_GET)) { foreach($_GET as $eachKey => $eachValue) { ${'param_' . $eachKey} = $eachValue; } }
Example :
$_GET['hello'] => 'world'
gonna be$param_hello = 'hello'
Then, your code.
First, you need to set the response var. For JSON, it's gonna be an array.$response = [];
For example, I'll use mt_rand() function.
This value gonna be saved in$response
array as['result']
key.$reponse['result'] = mt_rand($param_min, $param_max);
Now, the API is finished, so we need to write down response:
echo json_encode($response); die(); // Then end the script
This method is recommended and very efficient with AJAX requests (most used with APIs)
Using file_get_contents
Forget
$response
and json functions.
The best Content-Type for this way is this:header('Content-Type: text/plain');
And just echo the result:
echo mt_rand($param_min, $param_max);
I'm here for questions. And you have Internet, or PHP Manual for more info.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 乌班图ip地址配置及远程SSH
- ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
- ¥15 PSPICE制作一个加法器
- ¥15 javaweb项目无法正常跳转
- ¥15 VMBox虚拟机无法访问
- ¥15 skd显示找不到头文件
- ¥15 机器视觉中图片中长度与真实长度的关系
- ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
- ¥15 java 的protected权限 ,问题在注释里
- ¥15 这个是哪里有问题啊?