如何在php中使用CURL调用REST API?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在php中使用CURL调用REST API?相关的知识,希望对你有一定的参考价值。

当我尝试使用curl调用API时,我遇到了问题。我的php代码看起来像这样:

<html>
<head>
<body>
<span style="z-index:50;font-size:0.9em;">
<img src="https://theysaidso.com/branding/theysaidso.png" height="20"  width="20" alt="theysaidso.com"/>
<a href="https://theysaidso.com" title="Powered by quotes from   theysaidso.com" style="color: #9fcc25; margin-left: 4px; vertical-align:  middle;">
theysaidso.com</a></span>
<?php
       $service_url = 'http://quotes.rest/qod.json';
       $curl = curl_init($service_url);
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($curl, CURLOPT_POST, false);
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
       $curl_response = curl_exec($curl);
       curl_close($curl);
       $json_objekat=json_decode($curl_response);
       echo $json_objekat->contents->quotes->quote.'<br>';
       echo $json_objekat->contents->quotes->author.'<br>';    
?>
</body>
</head>

此代码在WAMP服务器上的根目录中保存为php文件。我使用WAMP服务器。它写在这个网站http://quotes.rest/qod.json上,你必须插入这个HTML。当我在WAMP上打开这个php页面时,它会显示警告:

注意:第18行的C: wamp www IzdavackaKuca javniServis.php中的未定义属性:stdClass :: $ contents

注意:尝试在第18行的C: wamp www IzdavackaKuca javniServis.php中获取非对象的属性

注意:尝试在第18行的C: wamp www IzdavackaKuca javniServis.php中获取非对象的属性

注意:未定义的属性:第19行的C: wamp www IzdavackaKuca javniServis.php中的stdClass :: $ contents

注意:尝试在第19行的C: wamp www IzdavackaKuca javniServis.php中获取非对象的属性

注意:尝试在第19行的C: wamp www IzdavackaKuca javniServis.php中获取非对象的属性

此链接上的JSON http://quotes.rest/qod.json如下所示:

{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "A loser doesn't know what he'll do if he loses, but talks about what he'll do if he wins, and a winner doesn't talk about what he'll do if he wins, but knows what he'll do if he loses.",
                "length": "184",
                "author": null,
                "tags": [
                    "failure",
                    "inspire",
                    "knowledge",
                    "winning"
                ],
                "category": "inspire",
                "date": "2016-05-11",
                "title": "Inspiring Quote of the day",
                "background":       "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
                "id": "KhjRMynny89MKxcGkEKF_QeF"
             }
        ]
    }
}

当我在php中将最后两行更改为:

   echo $json_objekat['contents']['quotes']['quote'].'<br>';
   echo $json_objekat['contents']['quotes']['author'].'<br>';   

它提醒:

致命错误:无法在第18行的C: wamp www IzdavackaKuca javniServis.php中使用stdClass类型的对象作为数组

当我编码时,我真的不知道如何调用这个服务器:

<?php
   $defaults = array(
        CURLOPT_URL             => 'http://quotes.rest/qod.json',
        CURLOPT_POST            => false,
        CURLOPT_HEADER          => false,
        CURLOPT_SSL_VERIFYPEER  => false,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_SSL_VERIFYHOST  => false,
    );
    $curl               = curl_init();
    curl_setopt_array($curl, $defaults);
    $curl_response      = curl_exec($curl);
    $json_objekat       = json_decode($curl_response);

    // DUMP THE CURL-ERROR INFORMATION:
    var_dump(curl_error($curl));
    curl_close($curl);
?> 

它提醒:

字符串''(长度= 0)

请帮忙!

答案

问题是因为您正在错误地访问引用和作者。 print_r($json_objekat)的产量表示:

contents是stdClass对象 引号是数组 再次引用的是索引为0,这又是stdClass对象

因此,请尝试访问引用和作者,如下所示:

$json_objekat->contents->quotes[0]->quote

$json_objekat->contents->quotes[0]->author
另一答案

我假设这是你打算做的:

    <?php
        $service_url     = 'http://quotes.rest/qod.json';
        $curl            = curl_init($service_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $curl_response   = curl_exec($curl);
        curl_close($curl);
        $json_objekat    = json_decode($curl_response);
        $quotes          = $json_objekat->contents->quotes;

        foreach($quotes as $intKey=>$objQuote){
            echo $objQuote->title       . '<br>';
            echo $objQuote->author      . '<br>';
            echo $objQuote->quote       . '<br>';
            echo $objQuote->background  . '<br>';
        }
    ?>

但请注意,使用相同的IP地址,每小时不能超过10个请求。因此,一旦您完成10个请求,您将被阻止,您必须等待另外1小时才能继续处理您的请求。希望这可以帮助......

另一答案
<?php
$conn = mysqli_connect("localhost","root","","mydatabase");

if(!$conn){
    die("Connection failed: " . mysqli_connect_error());
}

if(!function_exists("curl_init")) die("cURL extension is not installed");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://localhost/ketan/all_user.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
echo $result;
//print_r(json_decode($result));//To Decode Result
?>

Output

Output

all_user.php

<?php
$conn = mysqli_connect("localhost","root","","mydatabase");

if(!$conn){
    die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query($conn,"SELECT * FROM tblUser");

$data = array();

while ($row = mysqli_fetch_array($result)) {
    /*$result = array();
    $result['userId'] = $row['userId'];
    $result['firstName'] = $row['firstName'];
    $result['lastName'] = $row['lastName'];*/
    array_push($data, array('userId'=> $row['userId'],'firstName'=> $row['firstName'], 'lastName'=>$row['lastName'],
        'email'=>$row['email'], 'phoneNumber'=>$row['phoneNumber'], 'userImage'=>"user_images/".$row['userImage']));
}


$return['status']  = true;
$return['message'] = 'Success';
$return['data']    = $data;
header('Content-Type: application/json');
echo json_encode($return, JSON_PRETTY_PRINT);
$conn->close();

?>

以上是关于如何在php中使用CURL调用REST API?的主要内容,如果未能解决你的问题,请参考以下文章

在 PHP 中使用 curl 访问 REST API 时出现错误 401

使用 PHP cURL 通过 REST API 获取 JSON

如何在服务器端访问 PHP REST API PUT 数据?

PayPal REST API - 使用 PHP 和 curl 进入实时模式

Paypal REST api 调用适用于 cURL,但不适用于 C# 代码

OAuth、PHP、Rest API 和 curl 给出 400 Bad Request