如何使用 curl 将 JSON 发布到 PHP [英] How to post JSON to PHP with curl

查看:44
本文介绍了如何使用 curl 将 JSON 发布到 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能跑偏了,但我整个下午都在尝试运行 curl post 命令 在这个隐藏的 PHP 框架教程中.我不明白的是 PHP 应该如何解释我的 POST,它总是作为一个空数组出现.

curl -i -X POST -d '{"screencast":{"subject":"tools"}}' http://localhost:3570/index.php/trainingServer/screencast.json

(那里的斜线只是为了让我看起来不像个白痴,但我使用 PHP 5.2 从 Windows 执行此操作,也在 Linux 服务器上尝试过,与 Linux curl 相同的版本)

一定有我遗漏的东西,因为它看起来很简单,只是没有正确解释帖子,如果是这样,一切都会很好.

这是我得到的:

<前>HTTP/1.1 409 冲突日期:2009 年 5 月 1 日星期五 22:03:00 GMT服务器:Apache/2.2.8 (Win32) PHP/5.2.6X-Powered-By:PHP/5.2.6传输编码:分块内容类型:文本/html;字符集=iso-8859-1{"screencast":{"id":null,"subject":null,"body":null,"dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}}

解决方案

Jordans 对 $_POST 数组未填充的原因的分析是正确的.但是,您可以使用

$data = file_get_contents("php://input");

只需检索 http 正文并自己处理即可.请参阅PHP 输入/输出流.

从协议的角度来看,这实际上更正确,因为无论如何您都没有真正处理 http 多部分表单数据.另外,在发布请求时使用 application/json 作为内容类型.

I may be way off base, but I've been trying all afternoon to run the curl post command in this recess PHP framework tutorial. What I don't understand is how is PHP supposed to interpret my POST, it always comes up as an empty array.

curl -i -X POST -d '{"screencast":{"subject":"tools"}}'  
      http://localhost:3570/index.php/trainingServer/screencast.json

(The slash in there is just to make me not look like an idiot, but I executed this from windows using PHP 5.2, also tried on a Linux server, same version with Linux curl)

There must be something I'm missing because it seems pretty straightforward, the post just isn't be interpreted right, if it was, everything would work great.

This is what I get back:

HTTP/1.1 409 Conflict
Date: Fri, 01 May 2009 22:03:00 GMT
Server: Apache/2.2.8 (Win32) PHP/5.2.6
X-Powered-By: PHP/5.2.6
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1

{"screencast":{"id":null,"subject":null,"body":null,
         "dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}}

解决方案

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

这篇关于如何使用 curl 将 JSON 发布到 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆