繁体   English   中英

使用属性将代码卷曲到 PHP

[英]Curl code to PHP with properties

我有以下 Curl 代码,我使用 curl to PHP 转换器将其转换为 PHP 代码

curl https://a.klaviyo.com/api/v1/list/dqQnNW/members \
  -X POST \
  -d api_key=API_KEY \
  -d email=george.washington@example.com \
  -d properties='{ "$first_name" : "George", "Birthday" : "02/22/1732" }' \
  -d confirm_optin=true

我得到的代码是

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://a.klaviyo.com/api/v1/list/dqQnNW/members");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "api_key=API_KEY&email=george.washington@example.com&properties='{&confirm_optin=true");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

然而,这似乎并不正确,因为“属性”行没有被翻译成 PHP 代码。

如何将带有 $first_name 变量的“属性”行合并到我的 PHP 代码中?

是的,这绝对不正确,转换器搞砸了 CURLOPT_POSTFIELDS 行。

尝试

curl_setopt($ch,CURLOPT_POSTFIELDS,'api_key=API_KEY&email=george.washington@example.com&properties={ "$first_name" : "George", "Birthday" : "02/22/1732" }&confirm_optin=true');

反而。 如果你能被激怒,请向转换器的作者发送错误报告,这绝对是一个错误。

和 protip,在 php 中,您可能想使用 http_build_query 函数代替application/x-www-form-urlencoded -encoding 和 json_encode 用于 json 编码,例如

curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query ( array (
        'api_key' => 'API_KEY',
        'email' => 'george.washington@example.com',
        'properties' => json_encode ( array (
                '$first_name' => 'George',
                'Birthday' => '02/22/1732' 
        ) ),
        'confirm_option' => true 

) ) );

另请注意,您确定在 curl 示例中正确使用了此 api 吗? 它将application/x-www-form-urlencoded -encoding 与 json-encoding 混合在一起,这很不寻常。 如果正确,这是一个奇怪的设计选择。 如果我是你,我会仔细检查这是否是文档的正确行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM