如何通过PHP调用api并从中获取json文件

时间:2017-10-05 05:30:55

标签: php json .htaccess rest api

我想检查所有请求的网址,如果网址中包含“video”文件夹,请将其重定向到API文件。那么API给了我一个json文件,它只包含“respond:true”或“respond:false”。如果在json文件中有响应:true,则必须显示url,如果json文件包含response:false,则必须向用户显示预定义的简单403页面。

我知道第一部分可以通过.htaccess文件中的简单代码实现,如下所示:

RewriteRule ^your/special/folder/ /specified/url [R,L]

但我不知道如何做第二部分。我的意思是如何获取API的结果,它是以json文件的形式并检查它。

2 个答案:

答案 0 :(得分:1)

您可以使用CURL ..

获取请求

$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);

POST REQUEST

    $postdata = array(
        'name' => 'Arfan'
    );

    $url = "https://example.com/api/user/create";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);

    $json_response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

您还可以使用 file_get_content 来获取API数据。

$json = file_get_contents("$url")

答案 1 :(得分:1)

您可以执行第二部分(调用API和响应):使用curl调用API并根据其响应进行处理:

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, false);
 curl_setopt($ch, CURLOPT_URL, "api_url_here");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $api_response_json = curl_exec($ch);
 curl_close($ch);
 //convert json to PHP array for further process
 $api_response_arr = json_decode($api_response_json);

 if($api_response_arr['respond'] == true ){
    //code for success here
 }else{
    // code for false here
 }

请注意:来自API的Json响应取决于API响应,如果API以json格式给出响应(也可以基于params)。