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

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

问题描述:

我想检查所有请求的url,如果url中包含“video”文件夹,将其重定向到一个API文件。那么API给我一个只包含“respond:true”或“respond:false”的json文件。如果在json文件中有回应:true必须显示url,并且如果json文件包含respond:false,则必须向用户显示预定义的简单403页面。如何通过php调用api并从中获取json文件

我知道拳头的一部分,可以在.htaccess文件中一个简单的代码是这样的:

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

但我不知道该怎么办的第二部分。我的意思是如何获得API的结果,这是一个JSON文件的形式,并检查它。

您可以使用卷曲..

GET请求

$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请求

$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") 

可以执行第二部分(调用API和响应):呼叫使用基于其响应卷曲和进程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)。

+0

很好的解决方案。但我已经发现,如果我想保留基础url(用户请求的ulr),我不能使用.htaccess文件进行重定向!那么,我如何强制每个请求的url使用php文件被API检查? – shekoufeh

+0

@shekoufeh你可以在路由之前使用上面的代码,或者在index.php之前使用其他代码。相应地放置条件 – BSB

+0

我只是想要在视频文件被请求时执行此操作。没有php文件。我真的很困惑,在这部分... – shekoufeh