【问题标题】:call data from API in php using CURL使用 CURL 从 php 中的 API 调用数据
【发布时间】:2019-02-13 11:30:36
【问题描述】:

我正在寻找一个示例,以在 php 中使用 CURL 从 API 请求中调用数据。 目前我正在开发 vreasy 项目,我需要从它的 API 获取数据。但在 vreasy 的例子中,他们已经展示了一些这样的

curl -u "<your-api-key>:" -X GET "https://api.vreasy.com/reservations?status=ENQUIRY&expand=guest&fields=guest/fname,guest/lname,guest/email"

所以,我的问题是如何使用这个示例来处理我的 PHP 代码。我想要一个使用这种方法的 PHP 示例。 我是新手,如果这个问题看起来很愚蠢,我很抱歉。

我正在处理 wordpress 项目,需要从这个 API 检索到 wordpress 自定义帖子类型的数据。

我尝试过类似的方法。

<?php
echo 'asd';
$api_key = 'your-api-key';
$url = 'https://api.vreasy.com/reservations?status=ENQUIRY&expand=guest&fields=guest/fname,guest/lname,guest/email';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $api_key . ":"); // Normally you'd put a password after the colon, but you don't need it if you're using an API key
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$response_json = json_decode($response, true);

print_r($response_json);

curl_close($ch);

但没有回应。 谢谢

【问题讨论】:

  • 查看 PHP 手册中的 cURL 并试一试。如果您随后遇到特定问题,请回来向我们展示您尝试过的内容。 SO 不是代码转换服务。
  • @MagnusEriksson 我已经添加了代码,我已经尝试过了。但我无法弄清楚那有什么问题。我也在互联网上搜索过,几乎所有的答案都向我展示了这种类型的代码。你能帮帮我吗?
  • print_r 显示什么?
  • 空白页,什么都没有
  • 空白页可能是错误或根本没有结果。为确保,检查您的服务器错误日志。一个好主意是在本地 PHP 环境中打开display_errors。在此处阅读更多信息:How do I get PHP errors to display?

标签: php wordpress api curl


【解决方案1】:

试试这个代码。我已经添加了这些行 $error = curl_error($ch); print_r($error);

<?php


    echo 'asd';
    $api_key = 'your-api-key';
    $url = 'https://api.vreasy.com/reservations?status=ENQUIRY&expand=guest&fields=guest/fname,guest/lname,guest/email';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, $api_key . ":"); // Normally you'd put a password after the colon, but you don't need it if you're using an API key
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $response_json = json_decode($response, true);

    print_r($response_json);

    $error = curl_error($ch);

    print_r($error);

    curl_close($ch);

    exit;
?>

您将在localhost 上收到此错误。 SSL 证书问题

SSL 证书问题:无法获取本地颁发者证书

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 2018-01-21
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多