【发布时间】:2021-07-08 16:59:24
【问题描述】:
我有这个 cURL 命令,我需要使用 Guzzle 7 将其转换为 PHP。我已经研究了几天(嗯,不止几天),但进展不快。 cURL 命令使用 Simpli.fi api 在父组织下创建组织。
curl -i -X POST -H "X-App-Key: xxxx-xx-xx-xx-xxxxxx" -H "X-User-Key: xxxx-xx-xx-xx-xxxxxx" \
-H "Content-Type: application/json" \
-d '{
"organization": {
"name": "My New Organization",
"parent_id": "5786",
"custom_id": "<Put your organization identifier here or omit this optional field>"
}
}' \
"https://app.simpli.fi/api/organizations"
我可以使用这个网站转换它,但它不使用 Guzzle:https://onlinedevtools.in/curl 这是它给我的:
include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array(
'X-App-Key' => 'xxxx-xx-xx-xx-xxxxxx',
'X-User-Key' => 'xxxx-xx-xx-xx-xxxxxx',
'Content-Type' => 'application/json'
);
$data = '{\n "organization": {\n "name": "My New Organization",\n "parent_id": "5786",\n "custom_id": "<Put your organization identifier here or omit this optional field>"\n }\n }';
$response = Requests::post('https://app.simpli.fi/api/organizations', $headers, $data);
除了上面的转换代码之外,这是我迄今为止尝试过的:
public static function createOrganization()
{
self::init();
$client = new Client(['debug' => true]);
$request = $client->request('POST',
self::$baseUrl.'/organizations', [
'multipart' => [
[
'name' => 'data',
'contents' => "{'organization':{'name':'Pete's Pet Pagoda','parent_id':'1052385'}}",
],
],
'headers' => [
'x-app-key' => self::$appKey,
'x-user-key' => self::$userKey,
'Content-Type' => 'application/json',
]
]);
dd($response = $request->getStatusCode());
}
我遇到了很多不同的错误,但这是最新的:
curl_setopt_array():不能将 Output 类型的流表示为 STDIO FILE*
谁能告诉我我做错了什么?有什么遗漏吗?
更新:在进一步研究此问题并与 Laracast Slack 频道上的开发人员聊天后,我了解到这是在 Windows 系统上运行时['debug' => true] 选项的错误,并在此进行了描述GITHUB页面:https://github.com/guzzle/guzzle/issues/1413
我在 Windows 10 Pro 系统上运行。我通过将调试选项更改为使用 fopen() 来纠正它,如下所示:
'debug' => fopen('php://stderr', 'w'),
我使用 PHPStorm。它建议使用“wb”来使其二进制安全。更改后,发布请求工作正常。
【问题讨论】:
-
旁注:
{'organization':{'name':'Pete's Pet Pagoda','parent_id':'1052385'}}不是有效的 JSON。 JSON 需要为键和字符串值加上双引号。 -
我已经更改了上面答案中的json,因为它是错误的