如何通过PHP Curl从Rest API获取JSON数据? [英] How to get JSON data from Rest API by PHP Curl?

查看:110
本文介绍了如何通过PHP Curl从Rest API获取JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rest api,可以通过以下URL访问:" http://127.0.0.1:8000/api/thesis/?format=json ".现在,我想从中获取JSON数据.为了连接到api,我尝试如下使用PHP-Curl.但是我得到NULL!(这是我第一次使用php,任何帮助都会很棒!)

I have a Rest api which I can access by this url: "http://127.0.0.1:8000/api/thesis/?format=json". Now I want to get the JSON data from it. For connecting to the api I tried to use PHP-Curl as below. But I get NULL! (This is the first time I'm doing php any help will be great!)

<?php
$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
//initialize a curl session
$curl = curl_init();
//set options for the transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_URL, $service_url);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = var_dump(json_decode($curl_response, true));
print_r($curl_jason);
echo $curl_jason;
?>

推荐答案

我认为您应该使用 curl GET 方法

I think you should use GET method of curl like this

$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);

这篇关于如何通过PHP Curl从Rest API获取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆