duan02143 2015-08-22 21:31
浏览 35
已采纳

如何使用PHP制作API [关闭]

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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)