无法获取 cURL Windows 命令行将 JSON 传递给 PHP 并检索 PHP 中的变量,始终为 null

问题描述 投票:0回答:1

我尝试过来自世界各地的示例,结果都相同。我知道我错过的一定是一些简单的事情。我在 Windows 11 cmd 中运行,没有返回错误,它确实调用了 PHP 脚本,但无法获取 PHP 脚本中的 JSON。我也尝试了 http 和 https。

cURL Version:
curl 8.4.0 (Windows) libcurl/8.4.0 Schannel WinIDN
Release-Date: 2023-10-11
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS HSTS HTTPS-proxy IDN IPv6 Kerberos Largefile NTLM SPNEGO SSL SSPI threadsafe Unicode UnixSockets

命令如下:

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","age":30,"city":"New York"}' http://myserver/hello.php

下面是 PHP 脚本,请原谅注释掉的行,因为它们反映了我尝试过的不同内容。注意我想传递 JSON 而不是

http://myserver/hello.php?name=John Doe&...

你好.php

<?php
  //header('content-type: application/json');
  //$json = file_get_contents('php://input');
  //$data = var_dump(json_decode($json, true));
  //$data = var_dump(json_decode($_GET, true));
  $data = json_decode(file_get_contents('php://input'), true);
    //$data = json_decode($_POST);
    //$data = $_POST;
  //$dump = print_r($data);
  //$dump = print_r($data);
    //$arrayJSON = json_decode($str_json);
    
  //$data = json_decode($_POST);
  

    file_put_contents('test.txt', $data['name']);
?>
php json curl
1个回答
0
投票

原始 -d 中的问题与转义引号有关。我实际上会在 Linux 环境中使用它,我相信原来的 -d 会在 Linux 中工作,但我还没有测试它。

原创-d

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","age":30,"city":"New York"}' http://myserver/hello.php 

修复了 -d(至少对于 Windows)

curl -X POST -H "Content-Type: application/json" -d "{""name"":""John Doe"",""age"":30,""city"":""New York""}" http://myserver/hello.php
© www.soinside.com 2019 - 2024. All rights reserved.