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 如何用Thoony写ESP32温湿度检测无源蜂鸣器报警代码?
  • ¥20 部件内部的CT图像数据集
  • ¥15 Visual studio调用动态库
  • ¥15 双目摄像头标定后的校准文件
  • ¥15 powerbi矩阵增加度量值后出现对应关系错乱
  • ¥30 频率分析法分析绘制奈奎斯特图、波特图
  • ¥15 弹出来一万个系统找不到指定的文件框框,怎么解决
  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow