【发布时间】:2014-05-14 10:03:21
【问题描述】:
首先,我对 PHP 和 cURL 都很陌生
来自命令:
curl -i 'http://xxx:xxx/v2.0/tokens' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": {"tenantName": "xxx", "passwordCredentials": {"username": "admin", "password": "xxx"}}}'
我想使用 POST/GET 和 PHP 生成此命令的结果。我有一个 apache 服务器和工作 url。
我只是不知道如何制作一个可以使用 PHP 获取代码并生成输出到空页面的工作代码。
我一直在搜索示例,我知道您必须使用以下一些:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>
我只是不知道如何将 cURL 命令中的正确标志附加到 PHP 代码,可能还遗漏了一些重要的东西来包装代码。
在此先感谢,如果我不能很好地解释我的问题,我们深表歉意。
** ***编辑:* ****
所以我编写了一个代码,它可以满足我的需要,它从 PHP 页面上的 cURL 命令生成原始结果。 代码如下:
<?php
$request_body = '{"auth": {"tenantName": "xxx", "passwordCredentials": {"username": "admin", "password": "xxx"}}}';
$ch = curl_init('http://xxx:xxx/v2.0/tokens');
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$response = curl_exec($ch);
var_dump($response);
?>
现在的问题是,如果我可以操纵输出以更好的方式显示,现在它只是一个大字符串,某种形式的 JSON 漂亮打印会很棒。
【问题讨论】: