【问题标题】:using CURL in php to retrieve data from an api在 php 中使用 CURL 从 api 检索数据
【发布时间】:2015-10-05 09:02:54
【问题描述】:

我有一个在终端上运行良好的 api 链接。我想使用相同的 api 链接在 php 中使用 CURL 检索数据。我试过下面的代码:

<?php

// set up the curl resource

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'urlxxxxx');
// execute the request

$output = curl_exec($ch);

// output the profile information - includes the header

echo  "curl response is : <br> ".($output). PHP_EOL;

// close curl resource to free up system resources

curl_close($ch);
?>

但我得到的回应是:

卷曲响应是: { "error" : "JSON 语法错误:JSON 字符串格式错误,既不是数组、对象、数字、字符串也不是原子,在 /usr/share/perl5/JSON 的字符偏移量 0 之前(在 \"(字符串结尾)\" 之前) .pm 第 171 行。\n" }

我是 CURL 新手,请指导我解决问题。

【问题讨论】:

  • 您没有CURLOPT_POSTFIELDS 发送参数的选项。
  • 我不想发送任何参数,我只想检索数据。
  • API 需要 JSON 格式的参数。也许您需要发送一个空数组或对象。
  • 如果我删除 curl_setopt($ch, CURLOPT_POST, true);我得到错误 404
  • 你能显示运行正常的命令行版本吗?

标签: php json api curl


【解决方案1】:

添加:

curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");

所以你发送一个空的 JSON 对象作为参数。这是 PHP 的等价物

-d "{}"

从命令行。

要将其他数组放入帖子数据,请使用json_encode

$data = array('userId' => array(), 
              'user_list' => array("1", "2", "3", "4", "5", "6", "7", "8")
             );
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data);

【讨论】:

  • 如何添加这种输入格式 "array [ {\n\tinteger: userID;\n} ] user_list\n" ,作为 CURL_POSTFIELDS ?
  • 使用 json_encode 将 PHP 数组转换为 JSON。查看更新的答案。
  • 你能举个例子吗? ?
  • curl -v -H "Content-Type: application/json" -X POST 184.73.165.170:3000/api/3ace632b194e4366b821f7775b51cc4e/… -d "{\"userID\":[],\"user_list\":["1 ", "2", "3", "4", "5", "6", "7", "8" ]}" 现在如何设置 curl 帖子字段????
  • 只需创建一个包含所需数据的 PHP 数组,然后调用 json_encode()。我已经更新了答案以匹配该数据。
【解决方案2】:

您需要通过删除curl_setopt($ch, CURLOPT_POST, true);将方法设置为“GET”
或者提供有效的 JSON curl_setopt($curl, CURLOPT_POSTFIELDS, "{}");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多