PHP如何使用CURL

时间:2016-05-02 13:38:43

标签: php python curl

我需要执行此命令

root@debian:~# curl -X PUT -d '{ "date": "2.5.", "order": 2, "prize": 45 }' '[URL]'
PHP(或Python)中的

。但我不知道该怎么做。我试过这个:

$data = '{ "date": "2.5.", "order": 2, "prize": 45 }';
$data = json_encode($data);
echo $data;
$ch = curl_init([URL]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
echo $response;

但是这会回来:

{ "error" : "Error: No data supplied." }

知道如何在PHP / Python中重现它吗?

3 个答案:

答案 0 :(得分:2)

$url = "[URL]";

$data = array(
"date" => "2.5.",
"order" => "2",
"prize" => 45
);

$json_data = json_encode($data);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$content = curl_exec($ch);

curl_close($ch);

答案 1 :(得分:0)

subprocess.call或subprocess.run将执行您需要的操作,尽管输出将被转储到stdout,因此如果您想要操作返回的数据,还需要重定向它。但是,您也可以使用requests,就像其他一些评论者所建议的那样。

https://docs.python.org/3.5/library/subprocess.html

import subprocess
import tempfile

with tempfile.TemporaryFile() as tmp:
    subprocess.call(["curl", "-X", "PUT", "-d", '{ "date": "2.5.", "order": 2, "prize": 45 }', '[URL]'], stdout=tmp)
    tmp.seek(0)
    data = tmp.read()

答案 2 :(得分:0)

Accoridng to PHP docs,

http://php.net/manual/en/function.http-build-query.php

http_build_query接受数组或对象作为参数。 此外,json_encode返回一个字符串:

http://php.net/manual/en/function.json-encode.php

所以,你需要改变你使用它们的方式。

此外,使用http_build_query可能更为可取,因为它会对给定的参数进行url编码:

When POSTing an associative array with cURL, do I need to urlencode the contents first?

因此,您需要将数组传递给http_build_query函数才能使其正常工作:

示例(来自上面的链接):

  $curl_parameters = array(
    'param1' => $param1,
    'param2' => $param2
  );

  $curl_options = array(
    CURLOPT_URL => "http://localhost/service",
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query( $curl_parameters ),
    CURLOPT_HTTP_VERSION => 1.0,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false
  );

  $curl = curl_init();
  curl_setopt_array( $curl, $curl_options );
  $result = curl_exec( $curl );

  curl_close( $curl );