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.

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

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私